WPF中的共享样式

时间:2014-10-08 16:56:42

标签: wpf styling

如果我想在UserControl或UserControl的部分中创建TextBlockFontWeight="Bold"的所有TextAlignment="Right"元素,该怎么办?我可以为某个范围内的TextBlock元素设置一些样式,所以我不必重复所有这些属性吗?

2 个答案:

答案 0 :(得分:1)

是的,创建一个没有x:Key的样式,它将应用于该范围内指定TargetType的所有项目

例如,要使所有TextBlock仅在特定FontWeight="Bold"中包含TextAlignment="Right"UserControl,您可以使用以下内容:

<UserControl.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="TextAlignment" Value="Right" />
    </Style>
</UserControl.Resources>

答案 1 :(得分:0)

如果你把它放在你的资源中,你的所有文本块都会变成相同的。

<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>