【发布时间】:2011-07-18 17:11:08
【问题描述】:
我尝试使用ListBox 的ItemContainerStyle 中的触发器更改我的ListBoxItems 的Background 属性,如下所示:
<ListBox Height="100" HorizontalAlignment="Left" Margin="107,59,0,0" Name="listBox1" VerticalAlignment="Top" Width="239">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Lightblue"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" Value="Red"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Items>
<ListBoxItem Content="First Item"/>
<ListBoxItem Content="SecondItem"/>
<ListBoxItem Content="Third Item"/>
</ListBox.Items>
</ListBox>
我希望未选择的项目具有浅蓝色背景,悬停的项目(即当鼠标光标悬停在它们上方时)为黄色,而选定的项目为红色。
对于未选择和悬停的项目,这按预期工作,但所选项目仍具有其标准背景颜色(即蓝色,如果列表框有焦点,否则为浅灰色)。
我有什么遗漏吗?这种行为是否记录在某处?
感谢任何提示!
编辑
我知道覆盖默认系统颜色的解决方案(如Change selected and unfocused Listbox style to not be grayed out 中所述,无论如何感谢大家将此作为答案发布)。然而,这不是我想要做的。我更感兴趣的是为什么我的解决方案不起作用。
我怀疑ListItem 的标准ControlTemplate 定义了它自己的触发器,这些触发器似乎优先于由样式定义的触发器(也许有人可以确认这一点,并将我指向一些定义此行为的资源) .
与此同时,我的解决方案是为我的ListItems 定义一个ControlTemplate,例如:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Padding="2" SnapsToDevicePixels="true" Background="LightBlue" Margin="0">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
【问题讨论】:
-
这意味着您使用了正确的解决方案。没有标准 ControlTemplate 和没有画笔覆盖的解决方案。
标签: wpf background styles