Change WPF DataGrid cell background color based on cell value
WPF DataGrid allows customizing cell appearance based on cell value. However, applying styles directly to DataGridCell
affects the entire row, not individual cells.
The workaround is to target specific columns containing different cell contents. For example, suppose you want to highlight all cells in the "Name" column that have a value of "John."
TextBlock based cells
For columns containing TextBlocks, you can use the ElementStyle
in the column's Trigger
to change the Text
attribute based on the Background
value:
<code class="language-xml"><DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Style.Triggers> <Trigger Property="Text" Value="John"> <Setter Property="Background" Value="LightGreen"/> </Trigger> </Style.Triggers> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn></code>
Value Converter Method
An alternative is to use a value converter to convert the cell value to a brush:
<code class="language-csharp">public class NameToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string input = (string)value; switch (input) { case "John": return Brushes.LightGreen; default: return DependencyProperty.UnsetValue; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } }</code>
Usage in XAML:
<code class="language-xml"><Window.Resources> <local:NameToBrushConverter x:Key="NameToBrushConverter"/> </Window.Resources> <DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.ElementStyle> <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/> </DataGridTextColumn.ElementStyle> </DataGridTextColumn></code>
Direct attribute binding
You can also directly bind Background
to a property that returns the desired brush:
<code class="language-csharp">public string Name { get { return _name; } set { if (_name != value) { _name = value; OnPropertyChanged(nameof(Name)); OnPropertyChanged(nameof(NameBrush)); } } } public Brush NameBrush { get { switch (Name) { case "John": return Brushes.LightGreen; default: break; } return Brushes.Transparent; } }</code>
Binding in XAML:
<code class="language-xml"><DataGridTextColumn Binding="{Binding Name}"> <DataGridTextColumn.ElementStyle> <Setter Property="Background" Value="{Binding NameBrush}"/> </DataGridTextColumn.ElementStyle> </DataGridTextColumn></code>
The above is the detailed content of How can I conditionally change the background color of individual cells in a WPF DataGrid based on their values?. For more information, please follow other related articles on the PHP Chinese website!