Articles in this section
Category / Section

How to customize the Foreground color for cells in a column based on the cell content from Code behind?

1 min read

You can achieve your requirement by setting Style to GridColumn.CellStyle as in the below code example

public SfDataGridPage()
{
    InitializeComponent();
    Style style = new Style(typeof(GridCell));
    style.Setters.Add(new Setter() { Property = GridCell.ForegroundProperty, Value = new Binding("Freight", BindingMode.TwoWay, new StyleConverter()) });
    dataGrid.Columns[2].CellStyle = style;
}

 

Refer the below code example for writing a converter to customize the cell foreground based on conditions.

public class StyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        double _value = (double)value;
        if (_value >= 500)
            return Color.Green;
        return Color.Red;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}

 

Screenshot:

customized cells foreground color

 

You can download a working sample for this KB here.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied