Add a alternate color to ListView rows in WPF using XAML

How to add a alternate row style for Listview using Style and Style Triggers in WPF/C#


Using Alteration count you can add Datagrid like alternate background for ListViewItems. There is no alternate background property for ListView control in WPF, instead we can made this possible with style triggers.

Style triggers work with property and we can track the change with trigger value value.

Styles

The alternate color we want to apply is for ListViewItems , so we have to create a Itemcontainer style for ListView as follows.

    <Style TargetType="ListViewItem" x:Key="gridview_itemcontainer1" >
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="FontSize" Value="13.5"/>       
    </Style>

You can define the style as resource file or can define as ListView.Resources in your xaml portion of UI.

As ListViewResource

<ListView AlternationCount=2 >
  <ListView.Resources>
   <Style TargetType="ListViewItem" >
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="FontSize" Value="13.5"/>       
    </Style>
  </ListView.Resources>

<ListView/>

In our style we are define background and font using Setter. Likewise we can add some Style Triggers. We want to change the color of ListViewItems according to the AlternationIndex value.

Style.Triggers

Add the following style trigger section in our style.

<Style.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
       <Setter Property="Background" Value="LightBlue"></Setter>
    </Trigger>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
       <Setter Property="Background" Value="LightYellow"></Setter>
    </Trigger>
 </Style.Triggers>

We had added two trigger for checking the alternationIndex value and a associated setter for setting background property of ListViewItem.

Our style is finished and purpose is served.

If you are use resource file you can assign the style to Item container as ItemContainerStyle=”{DynamicResource <RESOURCEKEY>}”. Replace the RESOURCE KEY with your own style key.