Wednesday, August 26, 2009

How to set WPF ListView alternate row color

Another common task you might have to tackle when working with WPF ListView is setting the background color for the rows in an alternate fashion (odd rows and even rows - you know what I mean).

This is how you do it.

First thing, create a style element in your ResourceDictionary or if you don't have one drop it on the page itself:

<Style x:Key="alternatingListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<!-- setting up triggers for alternate background colors -->
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="White"></Setter>
</Trigger>
</Style.Triggers>
<!-- setting row height here -->
<Setter Property="Height" Value="30" />
</Style>

Now set the ItemContanerStyle on the actual ListView and set the AlternationCount attribute):

<ListView Name="recordContainer" ItemContainerStyle="{StaticResource alternatingListViewItemStyle}" AlternationCount="2" >
<ListView.View>
<GridView>
<!-- Just a few sample columns -->
<GridViewColumn Header="aField" />
<GridViewColumn Header="anotherField" />
<GridViewColumn Header="yetAnotherField" />
</GridView>
</ListView.View>
<!-- Whatever you might have in here -->
</ListView>

And this is all there is to it!

8 comments:

Niraj said...

There are different options availalbe however this is the best option to show alternate color in listview. Thanks for sharing good stuff.

Unknown said...

Thanks for this solution!!
Please fix the alternation index, it should start from 0, insted of 1.

Tim said...

Best method I've seen so far for this. Thanks!

Anonymous said...

superb.Really helpful.The most important things is your presentation skill is so simple that is very effective just like me i.e beginner in WPF.

Prabhat Saxena said...

Excellent example,
I m facing a problem to create run time listview that one was resolved but i was not able to set the alternative color...so now i a m able to create the style also ...


Thanks again...

Anonymous said...

I have an exception:
"Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception."
What could be the reason of that?

Anonymous said...

excellent work !! Kudos man !!

Muhammad Abbas said...

Your Are awsome
Thank u so much for such a nice blog. And awsome wpf help.
GOD bless you always.