【问题标题】:Can I get a WPF ListBox to inherit brushes from parent element?我可以让 WPF ListBox 从父元素继承画笔吗?
【发布时间】:2010-03-12 14:10:05
【问题描述】:
我的 WPF 窗口将其前景画笔设置为资源字典中的画笔,并且我希望窗口中的所有文本都具有这种颜色,因此我不会在其他任何地方触摸前景画笔。
文本框获得颜色
文本块获得颜色
按钮获得颜色
列表框不获取颜色,因此它们的内容也不获取。
有没有办法让列表框在这方面表现得像其他控件?
假设不是,而且这是设计使然,原因是什么?
编辑:
看来我的问题还不够清楚。
我了解如何创建样式和资源并将它们应用到ListBoxes;我想知道为什么我需要为某些控件执行此操作,而我 不需要 需要为其他控件执行此操作 - 为什么有些继承属性而其他不包含 - 以及是否有任何方法可以使它们全部以同样的方式继承。
【问题讨论】:
标签:
.net
wpf
xaml
listbox
【解决方案1】:
ListBox 和其他一些控件不继承 Foreground 属性的原因是它被默认样式的 Setter 显式覆盖。不幸的是,即使您为不包含 Foreground 属性设置器的 ListBox 分配了自定义样式,它仍然会在尝试继承其父级的值之前回退到使用默认样式。
确定属性值的优先顺序为:
- 局部值
- 样式触发器
- 模板触发器
- 样式设置器
- 主题风格触发器
- 主题样式设置器
- 属性值继承
- 默认值
由于 #6 是在控件的默认样式中定义的,因此 WPF 不会尝试确定 #7 的值。
【解决方案2】:
这是列表框项的样式:
<Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background"
Value="{StaticResource SelectedBackgroundBrush}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground"
Value="{StaticResource DisabledForegroundBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
现在,您要做的是修改它,以便静态资源“DisabledForegroundBrush”指向您的资源画笔。将此添加到您的 Window.Resource 标记中,您应该一切顺利。
【解决方案3】:
你可以这样做:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="root">
<ListBox>
<ListBox.Resources>
<Style TargetType="{x:Type ListBox}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Yellow"/>
<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="Red"/>
</Style.Resources>
</Style>
</ListBox.Resources>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
</ListBox>
</Page>
您可以使用绑定表达式来绑定到为您的应用程序定义的颜色资源,而不是 Color="Red"。