应用样式键

时间:2016-08-23 18:03:29

标签: wpf xaml

我有<ResourceDictionary>包含这个:

<Style TargetType="TextBlock">
    <Setter Property="FontFamily" Value="..\..\Fonts\#Roboto"/>
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="TextWrapping" Value="Wrap"/>
</Style>

这很好用。

现在我添加了另一种风格:

<Style x:Key="MyText" TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="FontWeight" Value="SemiBold"/>
</Style>

但是,在将<TextBlock>更改为<TextBlock Style="{StaticResource MyText}"/>后,只会选择第二个样式块中的样式。例如。现在忽略了FontFamilyFontSizeTextWrapping

如何为TextBlock设置默认值,然后添加到其中?我不想在{&#39;默认&#39;中添加x:Key。这种风格已在整个系统中使用。

1 个答案:

答案 0 :(得分:3)

我认为你只需要根据类型确定键控风格。见下面的例子。

请注意BasedOn="{StaticResource {x:Type TextBlock}}"

<Window.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="TextWrapping" Value="Wrap"/>
    </Style>
    <Style x:Key="MyText" TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red"/>
        <Setter Property="FontWeight" Value="SemiBold"/>
    </Style>
    <Style x:Key="MyAppendedStyles" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
        <Setter Property="Foreground" Value="Red"/>
        <Setter Property="FontWeight" Value="SemiBold"/>
    </Style>
</Window.Resources>
<StackPanel>
    <TextBlock Text="Hello" />
    <TextBlock Style="{StaticResource MyText}" Text="Style Key" />
    <TextBlock Style="{StaticResource MyAppendedStyles}" Text="Style Key" />
</StackPanel>