user3685285
user3685285

Reputation: 6586

WPF Binding to DataGrid Context from CellStyle

I have a WPF DataGrid that is bound to an observable collection of RowObjects with a bunch of bindable properties. To fill out the data in my table, I added DataGridTextColumns which bind to the properties of the RowObjects. For example:

<DataGrid ItemsSource={Binding RowCollection}>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Col1" Binding={Binding Property1Name, Mode=OneTime} IsReadOnly="True" />
        <DataGridTextColumn Header="Col2" Binding={Binding Property2Name, Mode=OneTime} IsReadOnly="True" />
        <DataGridTextColumn Header="Col3" Binding={Binding Property3Name, Mode=OneTime} IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

Let's say Property3 is an integer. I want the cells in Column3 to highlight to red when they are negative, yellow when it's zero, and green when it's positive. my first thought was to bind a System.Windows.Media.Color to the CellStyle of the DataGridTextColumn, but that doesn't seem to work directly. Any ideas?

Upvotes: 1

Views: 452

Answers (2)

hal9k2
hal9k2

Reputation: 127

I would recommend you to use Style that would change color of cell with help of IValueConverter

Check this : MSDN BLOG and experiment.

Best of luck.

Upvotes: 0

Lance
Lance

Reputation: 852

It's not easy, but you can use Converter for each cell Background

Style for one cell:

<Style x:Key="Col1DataGridCell" TargetType="DataGridCell">
    <Setter Property="Background" Value="{Binding Converter={StaticResource Col1Converter}}" />
</Style>

Converter for one cell:

public class Col1Converter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        var result = (RowObject)value;

        Color color;
        if (result.Value < 0) {
            color = Colors.Red;
        }
        else if (result.Value == 0) {
            color = Colors.Yellow;
        }
        else {
            color = Colors.Green;
        }

        return new SolidColorBrush(color);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }
}

Using in DataGrid:

<DataGridTextColumn Header="Col1" Style={StaticResource Col1DataGridCell} Binding={Binding Property1Name, Mode=OneTime} IsReadOnly="True" />

Upvotes: 1

Related Questions