0

I need to set the background for cells based on cell text values. For a single column, I need to show multiple backgrounds based on values. I am dynamically loading the values.

cell 1 - Value 1 - Red

Cell 2 - Value 2- green

Cell 3 - Value 1- Red.

Above cells are in the same column. How do I achieve this?

Raja vel
  • 11
  • 3

1 Answers1

0

Use an IValueConverter that converts your actual value to a certain color.

In code behind:

public class ValueToBgColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // logic here, and return a color, like
        return Brushes.Black;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

And in XAML:

<DataGridTemplateColumn.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Background" Value="{Binding Path=Value,Converter={StaticResource ValueToBgColorCoverter}}"/>
    </Style>
</DataGridTemplateColumn.CellStyle>
mami
  • 586
  • 1
  • 4
  • 14
  • You mentioned here to bind one property to set the background. But my question is to get the value from that cell and set background based on that value. DataMemberBinding="{Binding SubStatus}" – Raja vel Jul 11 '19 at 11:14
  • I just gave an example, you need to adjust the binding with the converter to bind to the property that is the source of the cell value. – mami Jul 11 '19 at 11:26