When a user clicks on an ListBoxItem, I want to it to be a bold larger font red background yellow
Everything works except the background. It seems that there is a standard (blue) background for the selected item. How do I override that and change the selected background yellow?
Here is the code:
<Window x:Class="AlternateListBox2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:AlternateListBox2">
<Window.Resources>
<local:Countries x:Key="countries"/>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Content" Value="{Binding Path=Name}"/>
<Setter Property="Margin" Value="2"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="FontSize" Value="18"/>
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ListBox
ItemsSource="{Binding Source={StaticResource countries}}"
Width="100"
Margin="10"
HorizontalAlignment="Left"
/>
</StackPanel>
</Window>
It can be done a lot simpler. The Background color for the selected ListBox items are taken from the SystemColors. So, what you need to do is override the SystemColors in the Resources of your ListBox:
The concept of overriding SystemColors, which ListBoxItem template will use for background/foreground is awful and often confuses folks who are new to WPF. Thus, my recommendation is to override ListBoxItem template and customize it.
This code should work for setting background. The problem is that you need to create a ControlTemplate and assign to ContentPresenter's Background property the value "Yellow".
Thanks Frances!! That did it for me, well somewhat. Here is my code that allows for the template to use the "StrColor" property for the selected and non-selected list items.