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

UWP override style properties without loosing other property definitions

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

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

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

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

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

那么我怎样才能保留基本样式呢?

在 WPF 中我可以使用 x:Type 属性并且只说

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

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

这正是您想要的:

<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 像素的橙色
  • 第二个 TextBlock 是 20 像素的橙色
  • 第三个 TextBlock 是 30 像素的橙色