Reputation: 2535
Why does this not work?
<ListBox>
<ListBox.Items>
<ListBoxItem>Foo</ListBoxItem>
<ListBoxItem>Bar</ListBoxItem>
<ListBoxItem>Text</ListBoxItem>
</ListBox.Items>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
I.e., Background
of ListBoxItem
does not change when it is selected.
I was hoping to achieve this simple behavior without having to override the default item template. Surely there is a simple solution here that I am just not seeing.
Update
The only way I have found which works in both Windows 7 AND Windows 8 is by overriding the default ItemContainerStyle
. This is made slightly less painful in that I can now right-click on the control in Visual Studio and Edit Style - Edit a copy... but this feels like overkill in that I am only ultimately changing the one line of XAML I commented out below. I am only showing a small relevant portion of the complete template I am forced to introduce/override.
Is there not a simpler way?
...
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Selector.IsSelectionActive" Value="True"/>
<Condition Property="IsSelected" Value="True"/>
</MultiTrigger.Conditions>
<!--<Setter Property="Background" TargetName="Bd" Value="#3D26A0DA"/>-->
<!-- Changed above line to the following line... -->
<Setter Property="Background" TargetName="Bd" Value="Red"/>
<Setter Property="BorderBrush" TargetName="Bd" Value="#FF26A0DA"/>
</MultiTrigger>
...
Upvotes: 1
Views: 1209
Reputation: 22702
Try add this in ListBox.Resources
and remove IsSelected
trigger:
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
</ListBox.Resources>
In system has default highlight brush depending on your system theme. To change this value, it is necessary to turn to SystemColors
.
Quote from MSDN
:
The SystemColors class provides access to system brushes and colors, such as ControlBrush, ControlBrushKey, and DesktopBrush. A system brush is a SolidColorBrush object that paints an area with the specified system color. A system brush always produces a solid fill; it can't be used to create a gradient.
You can use system brushes as either a static or a dynamic resource. Use a dynamic resource if you want the brush to update automatically if the user changes the system brush as the application is running; otherwise, use a static resource.
In .NET 4.5
system does not use SystemColors
, therefore, you should:
create the your Style/ControlTemplate
look for alternatives, for example here: List/Combo Box Background And Selected Colours Under .net 4.5
See this link, which shows how to remove the difference between the frameworks
Upvotes: 1