How to Inherit or Extend From Existing Styles

By Michael Detras

The Style class has a BasedOn property that lets us create a style which is based on an existing style. This feature helps us avoid redundant styles and cluttering in our XAML files.

Let's say we want all of our controls in our WPF application to have a margin of 4, a black background, and a height of 30. We can set these properties on all instances of our controls. However, doing this seems repetitive, assuming that there are many controls in your application. A better solution is to create a style that will be applied to these controls. Consider the following style. The TargetType is Control and won't be applied to the TextBox and ComboBox controls in the window.

<Window x:Class="WpfApplication1.MainWindow"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         
Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
         <Style TargetType="Control">
            <Setter Property="Background" Value="Black"/>
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Height" Value="30"/>
        </Style>
    </Window.Resources>
     <StackPanel>
        <TextBox Width="100" />
        <ComboBox Width="120" />
    </StackPanel>
</Window>

Using the BasedOn property, we can inherit the style and apply it to the controls of type TextBox and ComboBox. Take a look at the modified XAML.

<Window x:Class="WpfApplication1.MainWindow"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         
Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
         <Style x:Key="DefaultControlStyle" TargetType="Control">
            <Setter Property="Background" Value="Black"/>
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Height" Value="30"/>
        </Style>
        <Style TargetType="TextBox" BasedOn="{StaticResource ResourceKey=DefaultControlStyle}">
            <Setter Property="Foreground" Value="White"/>
        </Style>
        <Style TargetType="ComboBox" BasedOn="{StaticResource ResourceKey=DefaultControlStyle}"/>
    </Window.Resources>
     <StackPanel>
        <TextBox Width="100" />
        <ComboBox Width="120" />
    </StackPanel>
</Window>

If we run the application, the appearance of the TextBox and ComboBox will be as expected (has a black background, height of 30 and a margin of 4. In addition, we can also set other properties in the new styles. For example, in the TextBox style, we set the Foreground property to white.

Related FAQs

Example on how to apply a style to all the controls of the specified type in the application.
How to Inherit or Extend From Existing Styles  (1378 Views)