Change background color for selected ListBox item Change background color for selected ListBox item wpf wpf

Change background color for selected ListBox item


<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)


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>


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.