The .NET MAUI DataGrid provides support to customize the background of a DataGridCell based on a bool value.
We create a custom style targetting the DataGridCell in the Resource Dictionary.
<ContentPage.Resources>
<local:ColorConverter x:Key="converter"/>
<Style TargetType="syncfusion:DataGridCell" x:Key="customCellStyle">
<Setter Property="Background" Value="{Binding EmployeeStatus, Converter={StaticResource Key=converter}}"/>
</Style>
</ContentPage.Resources>
Then we set the key value to the CellStyle property of the particular column we want to customize.
<syncfusion:SfDataGrid ItemsSource="{Binding Employees}" CellTapped="SfDataGrid_CellTapped">
<syncfusion:SfDataGrid.Columns>
<syncfusion:DataGridNumericColumn MappingName="EmployeeID"
HeaderText="Employee ID"
Format="d"
ColumnWidthMode="Auto"
CellStyle="{StaticResource customCellStyle}"/>
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
In the cell tapped event we will modify the bool value, which will trigger the converter.
private void SfDataGrid_CellTapped(object sender, DataGridCellTappedEventArgs e)
{
if (e.RowData != null && viewModel.Employees.Contains(e!.RowData))
{
int index = viewModel.Employees.IndexOf((e.RowData as Employee)!);
viewModel.Employees[index].EmployeeStatus = !viewModel.Employees[index].EmployeeStatus;
}
}
In the converter we set the background based on the bool value.
public class ColorConverter : IValueConverter
{
object IValueConverter.Convert(object? value, Type targetType, object? parameter, CultureInfo info)
{
if ((bool)value!)
return Color.FromArgb("bde0fe");
else
return Colors.Transparent;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The following GIF demonstrates the customization of datagrid cell background based on bool value.
Take a moment to pursue this documentation, where you can find more about Syncfusion .NET MAUI DataGrid (SfDataGrid) with code examples. Please refer to this link to learn about the essential features of Syncfusion .NET MAUI DataGrid(SfDataGrid).
I hope you enjoyed learning about how to change the datagrid cell background based on bool value in .NET MAUI DataGrid?
You can refer to our .NET MAUI DataGrid's feature tour page to know about its other groundbreaking feature representations. You can also explore our .NET MAUI DataGrid Documentation to understand how to present and manipulate data. For current customers, you can check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our .NET MAUI DataGrid and other .NET MAUI components. If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac or feedback portal. We are always happy to assist you!