【发布时间】:2014-12-03 10:28:10
【问题描述】:
如果我想让 UserControl 或 UserControl 的部分中的所有 TextBlock 元素都具有 FontWeight="Bold" 和 TextAlignment="Right" 怎么办?是否可以在一定范围内为TextBlock 元素设置一些样式,这样我就不必重复所有这些属性?
【问题讨论】:
如果我想让 UserControl 或 UserControl 的部分中的所有 TextBlock 元素都具有 FontWeight="Bold" 和 TextAlignment="Right" 怎么办?是否可以在一定范围内为TextBlock 元素设置一些样式,这样我就不必重复所有这些属性?
【问题讨论】:
是的,创建一个没有x:Key 的样式,它将应用于该范围内指定TargetType 的所有项目
例如,要使所有 TextBlock 仅在特定的 UserControl 内具有 FontWeight="Bold" 和 TextAlignment="Right",您可以使用以下内容:
<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="TextAlignment" Value="Right" />
</Style>
</UserControl.Resources>
【讨论】:
如果你把它放在你的资源中,你所有的文本块都会变成一样的。
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="TextAlignment" Value="Right"/>
</Style>
或者,您也可以从TextBlock(例如BoldTextBlock)继承并将其用作目标类型。这样您就可以在与特殊文本块相同的控件中使用常规文本块
<Style TargetType="{x:Type BoldTextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="TextAlignment" Value="Right"/>
</Style>
【讨论】:
Grid.Column 这样的东西做到这一点。它似乎不像你在上面向我展示的那样工作。
Grid.Column 的含义。您的意思是使用特定样式来表示...只有一列?这有帮助吗? stackoverflow.com/a/853082/1732567
TextBlock 元素都在网格列 0 中。它们是标签 - 它们的输入元素都在网格列 1 中。我也想避免重复所有这些标记。跨度>
Style.Trigger 中使用<Trigger>。有关示例,请参见 this post。