Alternating Row Colours in a WPF ListView

Written by James Mansson on January 23, 2013 Categories: WPF

One common technique for making tabular data easier to read is to alternate the colour of data rows. I recently needed to add this effect to ListViews in a Windows application I had written using WPF.

Essentially, there are two steps to adding this effect to a particular Window template:

  1. Define a style that changes the background colour of a row based on the current alternation index.
  2. Set the ItemContainerStyle property to this style and AlternationCount property to 2.

A possible definition for the style, which should be placed in the Window.Resources section of the template, is:

<Window.Resources>
    <Style x:Key="AlternatingListViewItemStyle" TargetType="{x:Type ListViewItem}">
        <Style.Triggers>
            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                <Setter Property="Background" Value="LightBlue"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

This style will change the background colour to “LightBlue” when the AlternationIndex is 1.

The definition of the ListView needs to include the appropriate properties to apply this style properly. For instance:

<ListView ItemsSource="{Binding MyResultRows}"
 Name="MyListView" SelectionMode="Single" 
 ItemContainerStyle="{StaticResource AlternatingListViewItemStyle}"
 AlternationCount="2">

Clearly, the ItemContainerStyle property needs to be set to the name of the style. The function of the AlternationCount property is to specify the range of values through which the AlternationIndex should be cycled. The application will loop from 0 up to one less that the AlternationCount value, then start from 0 again. In this case, the effect will be to alternate between 0 and 1. This produces the desired effect of changing the background colour for every other row. The rows that are not changed will retain the default background colour for the control.

The above technique could be extended to produce a longer sequence of row colours by adding further triggers to the style and increasing the AlternationCount property. For instance, to create the sequence white, light blue and light gray, we could add the following trigger to the style definition:

<Trigger Property="ItemsControl.AlternationIndex" Value="2">
	<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>

We should then set the AlternationCount property to 3 for the ListView in question.

No Comments on Alternating Row Colours in a WPF ListView

Leave a Reply

Your email address will not be published. Required fields are marked *