Tuesday, November 17, 2009

A Simple Way to Change the Color of a Highlighted List View Item in XAML


I haven’t worked with Windows Forms that much since last December.  This year, I’ve worked on projects that involve ASP.NET, Linq to Sql, and web services.  I’m currently taking a class in WPF from Foothill College—you can visit Cal Schrotenboer’s page to see a description of the classes offered.  The classes are all conducted online and you don’t have to travel to the campus at all.  In addition, you can join the MSDN Academic Alliance program and get access to Microsoft software (include Expression Studio and Windows 7).

Learning WPF has been extremely fun and rewarding, but at times, frustrating!  I’m trying to do as much in XAML as possible.  I am doing an Image Viewer for my last class project, making great strides in some areas—and then getting stuck when I try to add what must be the most simple feature ever: changing the ListViewItem selected color. 

But due to my ignorance a simple task can take hours!  My only desire was to see the color of selected items changed to something other than the default.

My first take—which led me down the wrong path—was to add a Style Trigger.  The Trigger would set the Background color when IsSelected was true on the ListViewItem.  Or so I thought!

<Style TargetType="{x:Type ListViewItem}">
<Style.Resources>
<SolidColorBrush x:Key="SelectedBackgroundBrush" Color="DarkCyan" />
</Style.Resources>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" Value="Red">
</Setter>
</Trigger>
</Style.Triggers>
</Style>

Nope, no matter how I tried to massage that, it didn’t work.  Even more frustrating, I changed IsSelected to IsMouseOver and that worked fine.

As William Han explained to me on .NET Developer Forums, ListViewItem's base type ListBoxItem changes a Border background in control template instead of ListBoxItem.Background on the selected item.  William suggested a workaround could be modifying SystemColors.HighlightBrush since ListBoxItem's control template uses it.

Here’s what did work:

<Page.Resources>
<Style TargetType="ListViewItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"/>
</Style.Resources>
</Style>
</Page.Resources>  
<Grid>
<ListView>
<ListViewItem>Item 1</ListViewItem>    
<ListViewItem>Item 2</ListViewItem>
<ListViewItem>Item 3</ListViewItem>    
</ListView>
</Grid>

It’s a brute force method—changing the highlight color for all ListViewItem objects, but it works, as you can see by the Kaxaml screenshot on top.

0 comments:

Post a Comment