WPF DataGrid AlternatingRowBackground and RowStyle Priority

How to make my RowStyle available after AlternatingRowBackground ? I want elements that have IsOrange as true in order to have an Orange background, regardless of the background of alternating lines, which is not the case here.

XAML:

 <DataGrid Name="g" AlternatingRowBackground="Blue" AlternationCount="2" ... SelectionMode="Single"> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Style.Triggers> <DataTrigger Binding="{Binding IsOrange}" Value="Y"> <Setter Property="Background" Value="Orange" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.RowStyle> ... </DataGrid> 
+8
wpf wpfdatagrid
source share
2 answers

It's not a mistake. In Style you cannot override the local value specified for an alternating string. That is why it will not work

 <DataGrid AlternatingRowBackground="Blue" 

But if you set AlternatingRowBackground to Style , you can

 <DataGrid.Style> <Style TargetType="DataGrid"> <Setter Property="AlternatingRowBackground" Value="Blue"/> </Style> </DataGrid.Style> 

Thanks to this answer .

+12
source share

In my program, I have two classes in addition to the main window containing only one DataGird. Let's start with the first class:

MyClass.cs:

 public class MyClass { public bool IsOrange { get; set; } public string Name { get; set; } } 

I have only two properties, IsOrange indicates whether the string should be orange. ((Does not care about another property.))

Now the view model class contains only the MyClass collection.

MyClassViewModel.cs:

 public class MyClassViewModel { public ObservableCollection<MyClass> con { get; set; } public MyClassViewModel() { con = new ObservableCollection<MyClass>(); con.Add(new MyClass { IsOrange = true, Name = "Aa" }); con.Add(new MyClass { IsOrange = true, Name = "Bb" }); con.Add(new MyClass { IsOrange = false, Name = "Cc" }); con.Add(new MyClass { IsOrange = false, Name = "Dd" }); con.Add(new MyClass { IsOrange = false, Name = "Ee" }); con.Add(new MyClass { IsOrange = true, Name = "Ff" }); con.Add(new MyClass { IsOrange = true, Name = "Gg" }); con.Add(new MyClass { IsOrange = false, Name = "Hh" }); } } 

In MainWindow.xaml:

 <Grid> <DataGrid Margin="10" ItemsSource="{Binding Path=con}" > <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Style.Triggers> <DataTrigger Binding="{Binding Path=IsOrange}" Value="true"> <Setter Property="Background" Value="Orange" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.RowStyle> </DataGrid> </Grid> 

Finally, in MainWindow.xaml.cs:

 public partial class MainWindow : Window { MyClassViewModel VM = new MyClassViewModel(); public MainWindow() { InitializeComponent(); DataContext = VM; } } 

and this is the result:

enter image description here

You can send me your letter to send you the application.

Good luck :)

+2
source share

All Articles