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!

Friday, August 14, 2009

How to set WPF ListView selected item background color

After my last post I came across another common WPF task that could result in excruciating frustration if you're not using Expression Blend (or you just don't know enough about this shit nice framework): setting the color of the selected item in a ListView.

This is how you do it:

<Style TargetType="{x:Type ListView}">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Margin" Value="0"/>
<!-- here we go -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Black"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Gray"/>
<!-- other stuff -->

Hope it helps - if so you can express your gratitude by randomly upvoting some of my answers on stackoverflow.

Friday, August 7, 2009

How to set row height in WPF ListView

I've been checking out WPF lately for some prototyping work and came across something that's gotta be a very common show-stopper for beginners: I had a ListView element setup as a grid and no clue about how to set row height (without increasing font text - should go without saying).

This is a nice way of doing it (thanks stackoverflow):

<Style TargetType="ListViewItem">
<Setter Property="Height" Value="50" />
<!-- WHATEVER -->

That's what you get if you try to do some WPF magic without an Expression Blend license, which reminds me the good old days of editing html manually and feeling a God (except the God part).