【发布时间】:2026-01-24 08:05:01
【问题描述】:
我的问题出现在 .NET 3.5 SP1 中的 WPF 上,可以描述如下:
我有一个默认的Style 在我的 UI 中点击所有 TextBlock 元素。这就是它的外观:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
<Setter Property="Foreground" Value="Red"/>
</Style>
这适用于所有TextBlocks。除此之外,我还有一个Button 样式,包括一个看起来像这样(缩短)的ControlTemplate:
<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}" BasedOn="{x:Null}">
<Setter Property="Foreground" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
Height="24"
BorderBrush="{TemplateBinding BorderBrush}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextBlock.Foreground="{TemplateBinding Foreground}"/>
</Border>
<ControlTemplate.Triggers>...</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
注意ContentPresenter 中的TextBlock.Foreground="{TemplateBinding Foreground}" 行。这应该将按钮文本设置为绿色,事实上它在 Visual Studio 的设计器视图中也是如此。但是当我编译并运行程序时,按钮文本是红色的,文本颜色由默认的TextBlock 样式设置。我用 Snoop 验证了这一点。
如何防止默认TextBlock 样式覆盖TextBlock.Foreground 值? ContentPresenter 的 OverridesDefaultStyle 属性在这种情况下没有帮助。
有什么想法吗?
【问题讨论】:
标签: c# wpf xaml styles textblock