#1,200 – Overriding a Default Style

In WPF, you often set up default styles to set a series of properties on all instances of a certain type of element. Below, we set a default style that applies to all TextBlock elements, using the TargetType attribute. All properties in the style will be set for all instances of the TextBlock element.

<Window.Resources>
    <ResourceDictionary>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Purple"/>
            <Setter Property="FontStyle" Value="Italic"/>
        </Style>
    </ResourceDictionary>
</Window.Resources>

<StackPanel Margin="10">
    <TextBlock Text="Fafnir"/>
    <TextBlock Text="Siegfried"/>
    <TextBlock Text="Brynhildr"/>
</StackPanel>

1200_01

Sometimes you’ll be working in an environment where these default styles have been defined for you, but you want to override them.

The first way to override a default style is to define one of your own. Below, we define a named style and use it on the second TextBlock. (The style is added to the ResourceDictionary that we showed above).

<Style x:Key="BlueBig" TargetType="TextBlock">
   <Setter Property="Foreground" Value="Blue"/>
   <Setter Property="FontSize" Value="20"/>
</Style>
<TextBlock Text="Siegfried" Style="{StaticResource BlueBig}"/>

1200_02
The second way to override a default style is to revert the element to having no style at all using the x:Null markup extension. Below, the default style exists in our application but the first and third elements indicate that that they don’t want to use it. Notice that these TextBlocks appear normally.

<TextBlock Text="Fafnir" Style="{x:Null}"/>
<TextBlock Text="Siegfried" Style="{StaticResource BlueBig}"/>
<TextBlock Text="Brynhildr" Style="{x:Null}"/>

1200_03