How do I change the background color of a cell using WPF Toolkit Datagrid

Viewed 36827

I'm using the WPF toolkit datagrid, and I'd like to set the background color of a cell, not the row, based on the content of the cell.

For the sake of simplicity, lets say the column is called Foo and I'd like the background of the cell to be blue when Foo is 1, red when Foo is 2, Yellow when Foo is 3 and Green when Foo is greater than 3.

If I can do that, I'm pretty sure I can solve any of the more complex cases that I need to deal with.

4 Answers

A slightly different approaching is, instead of targeting the TextBlock element, which often leaves a border around the control, to the DataGridCell itself instead. In my case I already had a style I wanted to inherit from, I just needed to change background colours depending on the value:

<DataGridTextColumn 
    Width="*"
    Header="Status"
    Binding="{Binding EventStatus, Converter={StaticResource DescriptionAttributeConverter}}"
    HeaderStyle="{StaticResource DataGridColumnHeaderStyleCenterAligned}">

    <DataGridTextColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource DataGridCellStyleCenterAligned}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding EventStatus}" Value="1">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>

                <DataTrigger Binding="{Binding EventStatus}" Value="2">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

Might be of some use to people my situation.

The serge_gubenko will work well if your item inherits From INotifyPropertyChanged then when your property will change call to NotifyPropertyChanged("yourproperty")

Related