UWP覆盖样式属性而不会丢失其他属性定义

时间:2016-02-24 14:39:21

标签: c# xaml win-universal-app

我创建了一个UWP应用程序并定义了一些这样的样式:

<Style TargetType="TextBlock" >
<Setter Property="Foreground" Value="Orange" />
<Setter Property="Margin" Value="12" />
<Setter Property="FontSize" Value="18" />

所以,我所有的TextBlock都是橙色,边距为12px。一切都很好。但现在我想为Headlines定义第二种样式,它应该继承基本样式并覆盖额外定义的属性,如下所示:

  <Style x:Key="HeadlineStyle" TargetType="TextBlock">    
<Setter Property="FontSize" Value="32" />

但如果我这样做,所有其他样式定义都消失了(没有边距,没有着色)。

那我怎么能保持基本风格呢?

在WPF中,我可以使用x:Type属性,只需说

BasedOn="{StaticResource  {x:Type Button}}"

但是x:UWP中没有类型(我发现它不再受支持)

1 个答案:

答案 0 :(得分:3)

这完全符合您的要求:

<Grid.Resources>
  <Style TargetType="TextBlock" x:Key="medium">
    <Setter Property="Foreground" Value="Orange"/>
    <Setter Property="FontSize" Value="20"/>
  </Style>
  <Style TargetType="TextBlock" BasedOn="{StaticResource medium}">
    <Setter Property="FontSize" Value="10"/>
  </Style>
  <Style TargetType="TextBlock" x:Key="bigger" BasedOn="{StaticResource medium}">
    <Setter Property="FontSize" Value="30"/>
  </Style>
</Grid.Resources>
<StackPanel>
  <TextBlock Text="normal"/>
  <TextBlock Text="medium" Style="{StaticResource medium}"/>
  <TextBlock Text="bigger" Style="{StaticResource bigger}"/>
</StackPanel>
  • 第一个TextBlock是10-px orange
  • 第二个TextBlock为20-px orange
  • 第三个TextBlock为30-px orange
相关问题