在.NET 4.5 WPF中更改ListBox中SelectedItem的背景颜色
我想更改列表框的SelectedItem的背景颜色.我尝试了以下代码:
I want to change the background color of a ListBox's SelectedItem. I tried the below code :
<ListBox Grid.Column="0" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ItemsSource="{Binding Parents}" DisplayMemberPath="Title"
Height="35" FontSize="18" BorderThickness="0" Background="#FF2A2A2A"
Foreground="White" SelectedIndex="0">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="DodgerBlue" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="Transparent" />
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
但是我看不到SelectedItems的背景颜色有任何变化.有人可以指出以上XAML中的错误吗?
But I cannot see any change in SelectedItems's Background Color. Can anybody point the mistake in above XAML?
我也想针对特定的ListBox
使用这种样式,所以我不想更改ControlTemplate.
Also I want to use this style for this specific ListBox
, so I don't want to change ControlTemplate.
在.NET 4.5
系统中,默认情况下不使用SystemColors
,因此您应该:
In .NET 4.5
system does not use SystemColors
by default, therefore you should:
1)创建自己的样式/控件模板;
1) create your own Style/ControlTemplate;
2) create a BlankListBoxContainer
like in this
example:
<Style x:Key="BlankListBoxContainerStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="FocusVisualStyle" Value="{x:Null} "/>
</Style>
3)消除框架之间的差异,例如 this
:
3) remove the difference between the frameworks, like this
:
FrameworkCompatibilityPreferences.AreInactiveSelectionHighlightBrushKeysSupported = false;
在创建任何窗口之前,例如在InitializeComponent()
之前.
before any Window are created, for example before InitializeComponent()
.
从 MSDN
:
AreInactiveSelectionHighlightBrushKeysSupported:
AreInactiveSelectionHighlightBrushKeysSupported:
获取或设置一个值,该值指示应用程序是否应将
InactiveSelectionHighlightBrush
和InactiveSelectionHighlightTextBrush
属性用于不活动的所选项目的颜色.
Gets or sets a value that indicates whether the application should use the
InactiveSelectionHighlightBrush
andInactiveSelectionHighlightTextBrush
properties for the colors of inactive selected items.