我正在尝试将选定的ListBoxItem的背景颜色设置为白色,而不是系统颜色。我已经阅读了在此处找到的内容,并已经遵循或认为遵循了那里的建议(更改所选ListBox项的背景颜色,WPF如何在列表框失去焦点时更改列表框所选项目文本颜色,更改所选和未聚焦的Listbox样式以使其不变灰等)。
所有这些方法似乎都通过将HighlightBrush和ControlBrush设置为所选项目的Transparent来解决问题。 我有以下XAML代码可正确设置字体颜色,但无论刷子设置如何,背景始终是默认的透明蓝色。 我对WPF还不太熟悉,所以我肯定是错过了一些简单的东西。
<ListBox Width="Auto" Height="Auto" Grid.Column="0" BorderThickness="0" Background="#FFF3F3F3" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ListBox.ItemsSource>
<x:Array Type="{x:Type sys:String}">
<sys:String>String 1</sys:String>
<sys:String>String 2</sys:String>
<sys:String>String 3</sys:String>
<sys:String>String 4</sys:String>
</x:Array>
</ListBox.ItemsSource>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="FontSize" Value="16"/>
<Setter Property="Foreground" Value="#999999"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" HorizontalAlignment="Right" Margin="0,0,8,0" Background="Transparent"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我希望能得到任何指引。
编辑:
在阅读第一个答案后,发现有些微小的更改使其在Windows 7虚拟机上运行。这个应用程序在我的Windows 8计算机上开发并执行,它按预期工作。有什么想法可以让它在Windows 8和Windows 7上都能工作?
Style
,而不是默认的画笔。AlternationCount
是一个属性,你仍然可以在ListBox
上设置它,并且如果你有一个触发器,比如<Trigger Property="ListBox.AlternationIndex" Value="0"><Setter Property="Foreground" Value="Tomato" /></Trigger>
在<ControlTemplate.Triggers>
的Style
中,你会看到具有索引0作为AlternationIndex
的项目的Foreground
成功切换为Tomato
。 - Viv