Alternate row colors for WPF ListView

To set the alternate background colors for the listview in WPF, set the style and then refer that style object in the listview

  <Style x:Key="ListViewAlternateColors" TargetType="ListViewItem">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="Gray" />
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="LightGoldenrodYellow" />
                </Trigger>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="White" />
                </Trigger>
                
            </Style.Triggers>
        </Style>

and then set the style to the listview

 <ListView Height="170" ItemContainerStyle="{StaticResource ListViewAlternateColors}" Name="listView1" Width="719" AlternationCount="2" SelectionChanged="listView1_SelectionChanged" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Title}" />    
                    </StackPanel>
                    
                </DataTemplate>
            </ListView.ItemTemplate>
            
        </ListView>

Hope this helps someone.

Leave a Reply

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