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

Tobias Moe Thorstensen picture Tobias Moe Thorstensen · Aug 5, 2013 · Viewed 102.5k times · Source

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?

Answer

Nitesh picture Nitesh · Aug 5, 2013

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>