Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set DataGrid's row Background, based on a property value using data bindings

In my XAML code, I want to set the Background color of each row, based on a value of the object in one specific row. I have an ObservableCollection of z, and each of the z has a property called State. I started out with something like this in my DataGrid:

<DataGrid.RowStyle>     <Style TargetType="DataGridRow">         <Setter Property="Background"                  Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/>      </Style> </DataGrid.RowStyle> 

This is a wrong approach because x is not a property in my ViewModel class.

In my ViewModel class I have an ObservableCollection<z> which is the ItemsSource of this DataGrid, and a SelectedItem of type z.

I could bind the color to SelectedItem, but this will only change one row in the DataGrid.

How can I, based on one property change this rows backgroundcolor?

like image 532
Tobias Moe Thorstensen Avatar asked Aug 05 '13 08:08

Tobias Moe Thorstensen


1 Answers

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">     <DataGrid.RowStyle>         <Style TargetType="DataGridRow">              <Style.Triggers>                 <DataTrigger Binding="{Binding State}" Value="State1">                     <Setter Property="Background" Value="Red"></Setter>                 </DataTrigger>                 <DataTrigger Binding="{Binding State}" Value="State2">                     <Setter Property="Background" Value="Green"></Setter>                 </DataTrigger>             </Style.Triggers>         </Style>     </DataGrid.RowStyle> </DataGrid> 
like image 107
Nitesh Avatar answered Oct 06 '22 00:10

Nitesh