How to set DataGrid Background row based on property value using data bindings

In my XAML code, I want to set the Background color of each line based on the value of the object in one specific line. I have an ObservableCollection of z , and each of z has a property called State . I started with something like this in my DataGrid :

 <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Background" Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/> </Style> </DataGrid.RowStyle> 

This is the wrong approach because x is not a property in my ViewModel class.

In my ViewModel class, I have an ObservableCollection<z> , which is the ItemsSource this DataGrid and a SelectedItem type z .

I could bind the color to the SelectedItem , but this will change only one row in the DataGrid .

How can I change these backgroundcolor strings based on a single property?

+51
wpf xaml wpfdatagrid
Aug 05 '13 at 8:00
source share
2 answers

Use DataTrigger

  <DataGrid ItemsSource="{Binding YourItemsSource}"> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Style.Triggers> <DataTrigger Binding="{Binding State}" Value="State1"> <Setter Property="Background" Value="Red"></Setter> </DataTrigger> <DataTrigger Binding="{Binding State}" Value="State2"> <Setter Property="Background" Value="Green"></Setter> </DataTrigger> </Style.Triggers> </Style> </DataGrid.RowStyle> </DataGrid> 
+112
Aug 05 '13 at 8:12
source share
— -

The same thing can be done without a DataTrigger:

  <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Background" > <Setter.Value> <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}"> <Binding.ConverterParameter> <x:Array Type="SolidColorBrush"> <SolidColorBrush Color="{StaticResource RedColor}"/> <SolidColorBrush Color="{StaticResource TransparentColor}"/> </x:Array> </Binding.ConverterParameter> </Binding> </Setter.Value> </Setter> </Style> </DataGrid.RowStyle> 

Where BooleanToBrushConverter is the following class:

  public class BooleanToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return Brushes.Transparent; Brush[] brushes = parameter as Brush[]; if (brushes == null) return Brushes.Transparent; bool isTrue; bool.TryParse(value.ToString(), out isTrue); if (isTrue) { var brush = (SolidColorBrush)brushes[0]; return brush ?? Brushes.Transparent; } else { var brush = (SolidColorBrush)brushes[1]; return brush ?? Brushes.Transparent; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 
+11
Dec 14 '15 at 7:58
source share



All Articles