Wpf – How to inherit XAML style and override property of child element

wpfxaml

we just got started with XAML and are still fighting with basic issues:
Coming from CSS we'd like to define a generic button style with custom control template and then have a second style inherit everything from the first style using "basedon. This second style should then override properties such e.g. "foreground color" (which works) but also properties of child elements within our custom template such as the "background color" of e.g. an included border element etc. (which doesn't work).

What's the general approach to go about things like this? How far can we go with cascading styles?

Cheers!

Best Answer

You can use an inherited style with no key reference:

<Grid>
    <Grid.Resources>
        <!-- Definition of default appearance of a button -->
        <Style TargetType="Button" x:Key="Default">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="FontFamily" Value="Segoe Black" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="FontSize" Value="32pt" />
            <Setter Property="Foreground" Value="#777777" />
        </Style>
        <!-- Define general style that based is base on the default style of the button without a key reference-->
        <Style TargetType="Button" BasedOn="{StaticResource Default}"/>

        <!-- In sub style override the properties you need -->
        <Style BasedOn="{StaticResource Default}" TargetType="Button" x:Key="SubButton" >
            <Setter Property="FontSize" Value="8pt" />
        </Style>

    </Grid.Resources>

    <Button Content="Main" Height="51" HorizontalAlignment="Left" Margin="154,72,0,0" Name="button1" VerticalAlignment="Top" Width="141" />
    <Button Content="Sub" Style="{StaticResource SubButton}" Height="51" HorizontalAlignment="Left" Margin="154,162,0,0" Name="button2" VerticalAlignment="Top" Width="141" />
</Grid>
Related Topic