0

I know you can set a default style if you don't specify a x:Key property. (so it apply to all elements from the type specified in TargetType)

I want to use a key for inheritance (BasedOn property), but still keep it default. I thought about creating another style who is just based on on the previous one. like this:

<Style TargetType="Button" x:Key="name">
        //...
    </Style >
    <Style TargetType="Button" BasedOn="name"/>

But I would prefer it if there is a neater way to do it.

Shachar Har-Shuv
  • 666
  • 6
  • 24

2 Answers2

3

You can set its name with {x:Type} markup extension:

  <Style TargetType="{x:Type Button}" x:Key="{x:Type Button}">
            <Setter Property="Background" Value="Red"/>
  </Style>

This way it still is an implicit style but you can now inherit from it.

Here is a complete working sample:

 <Window.Resources>
        <Style TargetType="{x:Type Button}" x:Key="{x:Type Button}">
            <Setter Property="Background" Value="Red"/>
        </Style>

        <Style x:Key="AnotherStyle" TargetType="Button"  BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="FontSize" Value="22"/>
        </Style>
    </Window.Resources>

    <Grid Background="DimGray" Name="Grid" DataContext="{Binding ExpandoObject}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Grid.Row="1" Content="LOL" Style="{StaticResource AnotherStyle}"/>
    </Grid>

EDIT As commented below, you do not event need to set x:Key as you can access it using x:Type only

taquion
  • 2,667
  • 2
  • 18
  • 29
  • You are right. But you don't even need to add x:Key="{x:Type Button}" as WPF does it for you behind the scenes. So if you create an implicit style (without x:Key) you can still reference it using {StaticResource {x:Type Button}} – Pavel Dec 20 '17 at 22:06
  • Agree on that. I have edited my answer. – taquion Dec 20 '17 at 22:44
-1

You use StaticResource:

 <Style TargetType="Button" x:Key="name">
   //...
 </Style >
 <Style TargetType="Button" BasedOn="{StaticResource name}">
   //...
 </Style >
Luke Le
  • 728
  • 1
  • 9
  • 24
  • This is wrong, by giving an x:Key a value other than x:Type you will lose the implicit style behavior. – taquion Dec 20 '17 at 22:45