How to Set Alternating Row Color in WPF DataGrid

By Michael Detras

The WPF DataGrid is meant for showing a large amount of data. Due to this, it is confusing to see many rows without any alternating row colors.

The first way to set alternate row colors is by setting the AlternatingRowBackground property of the DataGrid.

<DataGrid
    
AutoGenerateColumns="False"
    
AlternatingRowBackground="LightBlue"
    
Loaded="DataGrid_Loaded">
    <DataGrid.Columns>
         <DataGridTextColumn Header="Column" Binding="{Binding}"/>                 
    </DataGrid.Columns>
</DataGrid>

I used the Loaded event of the DataGrid to fill it up with items.



Another way is to use the AlternationCount property, which is inherited from ItemsControl. To get the same DataGrid appearance, we can use the following code.

<DataGrid
    
AutoGenerateColumns="False"
    
AlternationCount="2"
    
Loaded="DataGrid_Loaded">
    <DataGrid.Columns>
         <DataGridTextColumn Header="Column" Binding="{Binding}"/>                 
    </DataGrid.Columns>
     <DataGrid.RowStyle>
         <Style TargetType="DataGridRow">
            <Style.Triggers>
                 <Trigger Property="AlternationIndex" Value="1">
                     <Setter Property="Background" Value="LightBlue"/>
                 </Trigger>                         
             </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

In the preceding XAML, we specified an AlternationCount value of 2. It means that a DataGridRow will have its AlternationIndex property set to either 0 or 1. Using AlternationCount gives us more control. Setting the AlternationCount to 3 means that possible AlternationIndex values are 0, 1, or 2. Applying an AlternationCount value of 3 to the previous example would look like the following figure.



How to Set Alternating Row Color in WPF DataGrid  (4197 Views)