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

Sur*_*ras 5 c# xaml win-universal-app

我创建了一个 UWP 应用程序并定义了一些样式,如下所示:

<Style TargetType="TextBlock" >
<Setter Property="Foreground" Value="Orange" />
<Setter Property="Margin" Value="12" />
<Setter Property="FontSize" Value="18" />
Run Code Online (Sandbox Code Playgroud)

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

  <Style x:Key="HeadlineStyle" TargetType="TextBlock">    
<Setter Property="FontSize" Value="32" />
Run Code Online (Sandbox Code Playgroud)

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

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

在 WPF 中,我可以使用 x:Type 属性,然后说

BasedOn="{StaticResource  {x:Type Button}}"
Run Code Online (Sandbox Code Playgroud)

但是 x:Type 在 UWP 中不可用(我发现它不再受支持)

Pet*_*SFT 5

这正是你想要的:

<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>
Run Code Online (Sandbox Code Playgroud)
  • 第一个 TextBlock 是 10 像素的橙色
  • 第二个 TextBlock 是 20 像素的橙色
  • 第三个 TextBlock 是 30 像素的橙色