Category / Section
How to change row background based on record in WPF DataGrid (SfDataGrid)?
1 min read
You can change the row background based on record by customizing the style in WPF DataGrid (SfDataGrid).
In the below code example, VirtualizingCellsControl’s Background is changed through based on record properties through converter.
XAML
<Style x:Key="rowstyle" TargetType="Syncfusion:VirtualizingCellsControl"> <Setter Property="Background" Value="{Binding UpdateSourceTrigger=PropertyChanged,Converter={StaticResource CustomRowStyleConverter}}" /> </Style>
C#
public class CustomRowStyleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return DependencyProperty.UnsetValue; if ((value as BusinessObjects).IsChecked) return new SolidColorBrush(Colors.Green) { Opacity = 0.7 }; return DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
When properties changed in data object the converter is not called to refresh the background at runtime. Since style setter binding is not bound to any property in data object. If we set the path in style setter binding, then converter will get called (Reference) to refresh the background.
You can overcome this problem by forcing the converter binding in SfDataGrid.View.RecordPropertyChanged event.
C#
this.datagrid.ItemsSourceChanged += datagrid_ItemsSourceChanged; void datagrid_ItemsSourceChanged(object sender, GridItemsSourceChangedEventArgs e) { if (this.datagrid.View != null) this.datagrid.View.RecordPropertyChanged += View_RecordPropertyChanged; } void View_RecordPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsChecked") { var datarow = this.datagrid.GetRowGenerator().Items.FirstOrDefault(row => row.RowIndex != -1 && row.RowData == sender); if (datarow != null) { var rowcontrol = (datarow as IRowElement).Element; BindingOperations.GetBindingExpression(rowcontrol, VirtualizingCellsControl.BackgroundProperty).UpdateTarget(); } } }