WPF Toolkit DataGridCell Style DataTrigger

I am trying to change the cell color to Yellow if the value has been updated in the DataGrid.

My xaml:

<toolkit:DataGrid x:Name="TheGrid" ItemsSource="{Binding}" IsReadOnly="False" CanUserAddRows="False" CanUserResizeRows="False" AutoGenerateColumns="False" CanUserSortColumns="False" SelectionUnit="CellOrRowHeader" EnableColumnVirtualization="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> <toolkit:DataGrid.CellStyle> <Style TargetType="{x:Type toolkit:DataGridCell}"> <Style.Triggers> <DataTrigger Binding="{Binding IsDirty}" Value="True"> <Setter Property="Background" Value="Yellow"/> </DataTrigger> </Style.Triggers> </Style> </toolkit:DataGrid.CellStyle> </toolkit:DataGrid> 

The grid is tied to a list of arrays (displaying a table of values โ€‹โ€‹of type excel). Each value in the array is a custom object that contains the IsDirty dependency property. The IsDirty property is set after changing the value.

When I ran this:

  • change value in column 1 = whole row yellow
  • change value in any other column = nothing will happen

I want only the changed cell to turn yellow, no matter which column it is in. Do you see something wrong with my XAML?

+3
source share
1 answer

The reason for this is because the DataContext set at the row level and does not change for each DataGridCell . Therefore, when you bind to IsDirty , it binds to a row-level data object property, not the first level.

Since your example shows that you have AutoGenerateColumns set to false, I assume that you yourself create columns that have something like DataGridTextColumn with the Binding attribute set to bind to the actual value field. To change the cell style to yellow, you need to change the CellStyle to each DataGridColumn as follows:

 foreach (var column in columns) { var dataColumn = new DataGridTextColumn { Header = column.Caption, Binding = new Binding(column.FieldName), CellStyle = new Style { TargetType = typeof (DataGridCell), Triggers = { new DataTrigger { Binding = new Binding(column.FieldName + ".IsDirty"), Setters = { new Setter { Property = Control.BackgroundProperty, Value = Brushes.Yellow, } } } } } }; _dataGrid.Columns.Add(dataColumn); } 

You can experiment with changing the DataContext each cell using the DataGridColumn.CellStyle . Perhaps only then can you bind a cell to "IsDirty" directly from the style at the grid level, just like you, without doing this for each column separately. But I do not have a real data model that you have to check.

+7
source

Source: https://habr.com/ru/post/1339873/


All Articles