Category / Section
                                    
                                How to change row background based on row state when underlying source is data table in WPF DataGrid (SfDataGrid)?
                
                
                    4 mins read
                
            
    You can change the row background based on RowState.Modified when binding WPF DataGrid (SfDataGrid) to DataTable using style for initial loading. You can also change the background for runtime changes using the DataTable.RowChanged event.
In the following code example, VirtualizingCellsControl’s background is changed based on the DataRow.RowState property in DataTable.
XAML:
xmlns:data="clr-namespace:System.Data;assembly=System.Data"
 
<Window.Resources>
     <Style TargetType="syncfusion:VirtualizingCellsControl">
         <Style.Triggers>
             <DataTrigger Binding="{Binding Row.RowState}" Value="{x:Static data:DataRowState.Modified}">
                  <Setter Property="Background" Value="LightYellow" />
             </DataTrigger>
         </Style.Triggers>
      </Style>
</Window.Resources>
SfDataGridBehavior :
public class SfDataGridBehavior : Behavior<SfDataGrid>
{
    protected override void OnAttached()
    {
         base.OnAttached();
         (AssociatedObject.ItemsSource as DataTable).RowChanged += SfDataGridBehavior_RowChanged;
    }
 
    private void SfDataGridBehavior_RowChanged(object sender, DataRowChangeEventArgs e)
    {
         var dataTable = (DataTable)AssociatedObject.ItemsSource;
         var record = AssociatedObject.View.Records.FirstOrDefault(row => (row.Data as DataRowView).Row == e.Row);
         var rowIndex = AssociatedObject.ResolveToRowIndex(record);
         Dispatcher.BeginInvoke
         ( System.Windows.Threading.DispatcherPriority. ApplicationIdle,
           new Action(() =>
           {
               if (e.Row.RowState == DataRowState.Modified)
               {
                   var currentRow = AssociatedObject.RowGenerator.Items.FirstOrDefault(r => r.RowIndex == rowIndex);
                   if (currentRow != null)
                   {
                        var element = currentRow.Element as VirtualizingCellsControl;
                        element.Background = new SolidColorBrush(Colors.LightYellow);
                   }
               }
           ));
    }
}