如何将所有文本块元素定义为相同的颜色
我们对大多数类型使用全局样式定义。然后我们在 app.xaml 文件中定义。使用 TextBlock 时,定义前景色是一个问题,因为它会更改使用 TextBlock 的所有控件(例如按钮的内容颜色)。 我们如何定义一个仅作用于特定 TextBlock 用法的全局样式?
当前有问题的用法:
<Style TargetType={x:Type TextBlock}>
<Setter Property="Foreground" Value="Red"/>
</Style>
We are using global styles definitions for most of the types. We define then in the app.xaml file. When using TextBlock it is a problem to define a foreground color because it changes all the controls using TextBlock (Button's content color for example).
How can we define a global style which will act only on specific TextBlock usages?
current problematic usage:
<Style TargetType={x:Type TextBlock}>
<Setter Property="Foreground" Value="Red"/>
</Style>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于我认为没有办法区分“您的”TextBlock 和其他控件的一部分,因此您的选择非常有限。
Style
并将Style="{StaticResource ColoredTextBlock}"
或Foreground="{StaticResource textBlockColor}"
添加到所有TextBlock
。这将是相当乏味且不DRY的。TextBlock
的类型并设置其样式。这具有上述解决方案的一些缺点(您必须记住这样做)。但它的重复次数要少得多。Since I don't think there is a way to differentiate “your”
TextBlock
s and those that are part of other controls, your options are quite limited.Style
and addStyle="{StaticResource coloredTextBlock}"
orForeground="{StaticResource textBlockColor}"
to allTextBlock
s. This would be quite tedious and non-DRY.TextBlock
and style that. This has some of the disadvantages of the above solution (you have to remember doing that). But it has much less repetition.这是因为
ContentPresenter
为字符串内容创建一个 TextBlock,并且由于该 TextBlock 不在可视化树中,因此它将查找应用程序级别资源。如果您在应用程序级别为 TextBlock 定义样式,那么它将应用于 ControlControls 内的这些 TextBlock。解决方法是为
System.String
定义一个DataTemplate
,我们可以在其中显式使用默认的 TextBlock 来显示内容。您可以将该 DataTemplate 放置在您定义 TextBlock 样式的同一字典中,以便该 DataTemplate 将应用于受您的样式影响的任何 ContentPresenter。将其添加到您的应用程序资源中,它应该适合您 -
在您的 xaml 中声明一个命名空间(如果尚未引用) -
编辑:检查此示例的工作位置..
This is because
ContentPresenter
creates a TextBlock for a string content, and since that TextBlock isn't in the visual tree, it will lookup to Application level resource. And if you define a style for TextBlock at Application level, then it will be applied to these TextBlock within ControlControls.A workaround is to define a
DataTemplate
forSystem.String
, where we can explicitly use a default TextBlock to display the content. You can place that DataTemplate in the same dictionary you define the TextBlock style so that this DataTemplate will be applied to whatever ContentPresenter effected by your style.Add this to your Application resources and it should work for you -
Declare a namespace in your xaml, if not referred already -
EDIT : Check this sample where its working..
只需在样式中提供 ax:key ,例如:
并在 TextBlock 控件样式中提及该键,无论您何时需要此特定的 TextBlock 样式,例如:
Just provide a x:key in the style, like:
and mention the key in the TextBlock control style, where ever you require this particular TextBlock style, like: