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}"/>
    <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}" />

No comments:

Post a Comment