This post is part of series called WPF Styles where you can find many different styles for your WPF application.
Today I will share with you a WPF DataGrid RowStyle that I used recently for my DataGrid. At some point of development I noticed that data inside my DataGrid was really hard to read because of each row had the same color, so I decided to apply a style that will alternate the color for the rows, just like we usually see in excel reports. After applying this style your DataGrid will look like this:
To achieve this we need to add a trigger to our style with AlternationIndex set to 1. Here is the XAML of the style:
<Style x:Key="RowStyleWithAlternation" TargetType="DataGridRow"> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="Background" Value="GhostWhite"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="ContextMenu" Value="{x:Null}"/> <Style.Triggers> <Trigger Property="AlternationIndex" Value="1"> <Setter Property="Background" Value="#FFD0D0E0"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#F9F99F"/> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="#F9F99F" /> </Trigger> <Trigger Property="Validation.HasError" Value="True" > <Setter Property="Effect"> <Setter.Value> <DropShadowEffect Color="Red" ShadowDepth="0" BlurRadius="20" /> </Setter.Value> </Setter> <Setter Property="BorderThickness" Value="2" /> <Setter Property="BorderBrush" Value="Red" /> <Setter Property="Foreground" Value="Blue" /> <Setter Property="FontSize" Value="12" /> </Trigger> </Style.Triggers> </Style>
This RowStyle will make your DataGrid look clearly and easier to read. Just don't forget to apply the style in the DataGrid definition:
<DataGrid Name="dataGrid1" RowStyle="{StaticResource RowStyleWithAlternation}" />
This is nice, but for me it somehow not working especially that "AlternationIndex" stuff :(
ReplyDeleteMaybe it's not working because I have data-binding in XAML and the data is collected in ViewModel? Please help!
ReplyDeleteNice. But the given example only works if you add this attribute to the DataGrid element:
ReplyDeleteAlternationCount="2"
Thank you so much anonymous (The one above this ^^) you saved me a lot of time
ReplyDelete