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}">
<!-- setting up triggers for alternate background colors -->
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"></Setter>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="White"></Setter>
<!-- setting row height here -->
<Setter Property="Height" Value="30" />

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

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

And this is all there is to it!


Niraj said...

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

Yaniv 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!

refat38 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 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 !!

Malik Muhammad Abbas said...

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