How to change the Background of a selected ListBox item.

In this article I would like to explain how to easily change the background color of a selected ListBox item. Sometimes common background color (I believe always) looks awful.

After right click:


After selected on other item the blue color isn’t disappeared:


If you select an item in a ListBox it gets the default selection color (usually blue) as background. Even if you specify a custom data template. The reason is that this color is defined outside of the data template.

So the easiest way to deal with these backgrounds is to locally override the highlight and control brushes of the system colors.

<Style x:Key=“myListboxStyle”>

<Style.Resources>

<!– Background of selected item when focussed –>

<SolidColorBrush x:Key=“{x:Static SystemColors.HighlightBrushKey}”
Color=“Red” />

<!– Background of selected item when not focussed –>

<SolidColorBrush x:Key=“{x:Static SystemColors.ControlBrushKey}”
Color=“Green” />

</Style.Resources>

</Style>

However, to the best of my belief it’s not a good solution to switch system colors. What is needed is a change to the ItemContainerStyle like this:


<!–ListBox style–>

<Style x:Key=”UsualListBoxItem” TargetType=”ListBoxItem”>

<Setter Property=”FocusVisualStyle” Value=”{x:Null}” />

<Setter Property=”Template”>

<Setter.Value>

<ControlTemplate TargetType=”ListBoxItem”>

<Border x:Name=”Border” Padding=”2″ SnapsToDevicePixels=”true”>

<ContentPresenter />

</Border>

<ControlTemplate.Triggers>

<Trigger Property=”IsSelected” Value=”true”>

<Setter TargetName=”Border” Property=”Background” Value=”Transparent”/>

</Trigger>

</ControlTemplate.Triggers>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

You can see that the ItemTemplate is set too which controls the layout of the data in each ListBoxItem. The ItemContainerStyle contains the template for the ListBoxItem – the one where I changed the selected item color. And now I got the behavior which I want.


In conclusion I would like to maintain that you can do many different effects with this. For example this funny one:


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s