Please can I have simple code to bind cell color to data?

Feb 22, 2009 at 12:12 AM
I am sure lot of people done it. I spent some time but cant find sutisfactory solution.

could u please share -how would you bind cell color to a property of an item bound to the grid thru observable collection? say i have two properties Price and IsUp and i want to display price red or green based on IsUp. grid binding and collection do not change, only the properties get updated in code.

what is the binding syntax good for that?

what are the other possibilities? data triggers?

thank you
Feb 22, 2009 at 2:16 PM
Edited Feb 22, 2009 at 2:24 PM
Here is the detailed solution for people of same WPF level as myself :)

NB: the solution for non-autogeneratecolumns; the solution is the same fast as if without colouring (!)

1. Add namespace to the Window element (very first element in XAML)

xmlns
:my="http://schemas.microsoft.com/wpf/2008/toolkit"

2. Add cell style with style triggers in your resources (e.g. your Window resources):

<Window.Resources>
    <Style x:Key="DataGridCellStyle" TargetType="{x:Type my:DataGridCell
}">
        <Style.Triggers
>
            <DataTrigger Binding="{Binding IsPriceUp}" Value
="true">
                <Setter Property="Foreground" Value
="Green" />
            </DataTrigger
>
            <DataTrigger Binding="{Binding IsPriceUp}" Value
="false">
                <Setter Property="Foreground" Value
="Red" />            
            </DataTrigger
>
        </Style.Triggers
>
    </Style
>
. . .

3. Bind the column cell style

<my:DataGrid . . . AutoGenerateColumns="False">
    <my:DataGrid.Columns
> . . .
        <my:DataGridTextColumn Binding="{Binding Path=Price}" Header="Price" 
                        CellStyle
="{StaticResource DataGridCellStyle
}" />

4. Implement change notifications in C#.. eg:

    IsPriceUp = newPrice >
this.Price;
    
this.Price = newPrice;
    NotifyPropertyChanged(
"Price");
    NotifyPropertyChanged("IsPriceUp");

Enjoy ! :)