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:
You can download a working sample for this KB here.