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)


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

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

3. Bind the column cell style

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

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

    IsPriceUp = newPrice >
this.Price = newPrice;

Enjoy ! :)