WPF: Changing the background of selected items in a ListBox

When you select an item in a ListBox, the background will be set to the default system background colour.

You can override the background by defining a style for the ListBox:

<Window.Resources>
    <Style x:Key="ListBoxStyle">
        <Style.Resources>
            <SolidColorBrush
              x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
        </Style.Resources>
    </Style>
</Window.Resources>

Now, define a ListBox, and let it use the style that we just defined:

<ListBox Style="{StaticResource ListBoxStyle}" HorizontalAlignment="Left"
        Margin="120,96,0,0" Width="151"
        IsSynchronizedWithCurrentItem="True" Height="92" VerticalAlignment="Top">
    <ListBoxItem>Item 1</ListBoxItem>
    <ListBoxItem>Item 2</ListBoxItem>
    <ListBoxItem>Item 3</ListBoxItem>
    <ListBoxItem>Item 4</ListBoxItem>
    <ListBoxItem>Item 5</ListBoxItem>
</ListBox>

The selected items will now have a red background:

You can also define a foreground colour. Add the following line to the style definition to make the foreground of selected items blue:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Blue" />
Advertisement

0 Responses to “WPF: Changing the background of selected items in a ListBox”



  1. Leave a Comment

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 )

Connecting to %s




Twitter Updates

del.icio.us


Follow

Get every new post delivered to your Inbox.