Add a alternate color to ListView rows in WPF using XAML

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.


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

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 >
   <Style TargetType="ListViewItem" >
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="FontSize" Value="13.5"/>       


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.


Add the following style trigger section in our style.

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

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.