Alternate Row Colors in ListBox in WPF

Alternate Row Colors in ListBox in WPF:

Here I am going to explain you how you can set the alternate row colors differently. For this I am using ListBox control using WPF.

For this first you have to define a style on Type of ListBoxItem. Below is the example:

<Style x:Key="AlternatingListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Style.Triggers>

<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="LightCyan"></Setter>
</Trigger>

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

</Style.Triggers>
</Style>

Alternate Row Colors in ListBox in WPF

 

Now you have to use this style on your application where this Listbox is used. Below is the code:

<ListBox ItemsSource="{Binding Users}" IsSynchronizedWithCurrentItem="True" AlternationCount="2" ItemContainerStyle="{StaticResource AlternatingListBoxItemStyle}">
<ListBox.ItemTemplate>
<DataTemplate DataType="desktop:UserViewModel">
<StackPanel>
<TextBlock Text="{Binding FullName}"/>
<TextBlock Text="{Binding Email}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

 

Written by 

Leave a Reply

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