【发布时间】:2018-08-27 09:20:22
【问题描述】:
我有一个全局样式 (Application.Resources) 来设置所有 TextBlocks 的前景。
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Brown"/>
</Style>
这很好用。
现在我尝试覆盖所选 ListBoxItem 内 TextBlock 的前景,这是默认 ContentPresenter 内容的一部分。
我为 ListBoxItem 创建了一个新的全局样式:
<Style TargetType="ListBoxItem">
<Setter Property="Foreground" Value="Orange" />
<Setter Property="Background" Value="Aqua"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Brown" />
<Setter Property="Foreground" Value="Aqua" />
</Trigger>
</Style.Triggers>
</Style>
背景效果很好。
但是 Foreground 仍然具有来自 TextBlock 的全局样式的画笔形式。 在使用 Binding 的解决方案中设置前景的最佳方式是什么?
【问题讨论】:
-
如果你想“覆盖选定 ListBoxItem 内 TextBlock 的前景” 为什么不在模板内放置一个 TextBlock,而不是 ContentPresenter?
-
这也是我的第一个想法。但是,那会被什么束缚呢?
-
Text="{Binding}"如果项目是字符串或项目类具有适当的 ToString 方法。否则绑定到项目类的某些属性。 -
是的,但是如果我将它与
Text="{Binding}"绑定,那么我将失去DisplayMemberPath-Feature。如果我将它绑定到模型的特定属性,我需要为每个模型一个特定的模板(样式)。