Change background color for selected ListBox item
I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey
instead of ControlBrushKey
:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>
Hope this helps someone out.
Or you can apply HighlightBrushKey directly to the ListBox. Setter Property="Background" Value="Transparent" did NOT work. But I did have to set the Foreground to Black.
<ListBox ... >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
</Style>
</UserControl.Resources>
and
<ListBox ItemsSource="{Binding Path=FirstNames}"
ItemContainerStyle="{StaticResource myLBStyle}">
You just override the style of the listboxitem (see the: TargetType is ListBoxItem)
You need to use ListBox.ItemContainerStyle.
ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.
juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter
for the Background property.