kay00
kay00

Reputation: 447

WPF: Set a cell color based on other multiple values in other columns?

I want to change the Abs(Diff) column. This has to be in Abs(Diff) because the viewer wants to see it this way.

 ID  | TYPE| CURRENT VALUE | TARGET       | ABS(Diff)
  1  | Sell| 10            |  11          | 1        --> Color Red
  2  | Sell| 11            |  10          | 1        --> Color Green
  3  | BUY | 10            |  9           | 1        --> Color Green
  4  | BUY | 10            |  11          | 1        --> Color Red

The meaning: Row 1: I have an item to sell. Current Market value is 10, I am looking to sell when it is at least(Target) 11. This does not meet my requirement. The color should be red in the cell for Abs(Diff)

I have looked at this. Change DataGrid cell colour based on values But this seems to be one value only. How do I look at multiple columns?

Upvotes: 0

Views: 2525

Answers (2)

Sheridan
Sheridan

Reputation: 69979

You could add a bool property named IsPositive that signifies whether the ABS(Diff) value is positive or negative. Maybe something like this:

public bool IsPositive
{
    get { return Diff >= 0; }
}

Then you'd need to do this to make sure that it updates in the UI when the Diff value changes:

public double Diff 
{
    get { return diff; }
    set
    {
        diff = value;
        NotifyPropertyChanged("Diff");
        NotifyPropertyChanged("IsPositive");
    }
}

Then you should be able to do something like this (adapted from the example in your linked question):

<DataGridTextColumn Binding="{Binding Abs}">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsPositive}" Value="True">
                    <Setter Property="Background" Value="LightGreen" />
                </DataTrigger>
                <DataTrigger Binding="{Binding IsPositive}" Value="False">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Abs}" Value="0">
                    <Setter Property="Background" Value="Black" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

Upvotes: 4

Manish Basantani
Manish Basantani

Reputation: 17509

But this seems to be one value only. How do I look at multiple columns?

If that's the 'only' problem, you should be creating another property in your ViewModel public bool ShouldColor, and have the desired logic there.

Or, you can achieve that by using MultiBinding

Upvotes: 2

Related Questions