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”