我的问题出现在 .NET 3.5 SP1 中的 WPF 中,可以描述如下:
我有一个默认的Style
击中所有TextBlock
我的用户界面中的元素。看起来就是这样:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
<Setter Property="Foreground" Value="Red"/>
</Style>
这对所有人来说都很好TextBlock
s。除此之外我还有一个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>
注意这条线TextBlock.Foreground="{TemplateBinding Foreground}"
in the ContentPresenter
。这应该将按钮文本设置为绿色,事实上它在 Visual Studio 的设计器视图中也是如此。但是当我编译并运行程序时,按钮文本是红色的,文本颜色是默认设置的TextBlock
风格。我和史努比验证了这一点。
如何防止默认TextBlock
风格从覆盖TextBlock.Foreground
价值?这OverridesDefaultStyle
的财产ContentPresenter
在这种情况下没有帮助。
任何想法?
请参阅答案 5这个链接
发生这种情况是因为
ContentPresenter 创建一个 TextBlock
对于字符串内容,从那时起
TextBlock 不在视觉树中,它
将查找应用程序级别
资源。如果你定义了一种风格
对于应用程序中的文本块
水平,然后它将被应用到
ContentControl 中的这些 TextBlock
解决方法是定义一个
System.String 的 DataTemplate,其中
我们可以显式地使用默认值
TextBlock 显示内容。你
可以将该 DataTemplate 放在
您定义的同一字典
TextBlock 样式,这样
数据模板将应用于
无论 ContentPresenter 受什么影响
你的风格。
尝试将其添加到 ResourceDictionary
<DataTemplate DataType="{x:Type sys:String}">
<TextBlock Text="{Binding}">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}"/>
</TextBlock.Resources>
</TextBlock>
</DataTemplate>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)