Marco Rehmer
Marco Rehmer

Reputation: 1093

UWP override style properties without loosing other property definitions

I create an UWP App and define some styles like this:

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

So, all my TextBlocks are orange and have a margin of 12px. All fine. But now I want to define a second style for Headlines, which should be inherit the base style and just override the extra defined properties, like this:

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

But if I do it this way, all other style definitions are gone (no margin, no coloring).

So how could I keep the base style?

In WPF I can use the x:Type attribute and just say

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

But x:Type are not available in UWP (and what I found it is no longer supported)

Upvotes: 5

Views: 2357

Answers (1)

Peter Torr
Peter Torr

Reputation: 12019

This does exactly what you want:

<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>
  • The first TextBlock is 10-px orange
  • The second TextBlock is 20-px orange
  • The third TextBlock is 30-px orange

Upvotes: 5

Related Questions