Saturday, July 28, 2012

WPF DataGrid RowStyle (AlternationIndex)

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:

WPF DatagridRow style with AlternationIndex set to 1

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}"/>
        <Trigger Property="AlternationIndex" Value="1">
            <Setter Property="Background" Value="#FFD0D0E0"/>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="#F9F99F"/>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="#F9F99F" />
        <Trigger Property="Validation.HasError" Value="True" >
            <Setter Property="Effect">
                    <DropShadowEffect Color="Red" ShadowDepth="0" BlurRadius="20" />
            <Setter Property="BorderThickness" Value="2" />
            <Setter Property="BorderBrush" Value="Red" />
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="FontSize" Value="12" />
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}" />


  1. This is nice, but for me it somehow not working especially that "AlternationIndex" stuff :(

  2. Maybe it's not working because I have data-binding in XAML and the data is collected in ViewModel? Please help!

  3. Nice. But the given example only works if you add this attribute to the DataGrid element:


  4. Thank you so much anonymous (The one above this ^^) you saved me a lot of time