#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,200 – Overriding a Default Style

  1. Pingback: Dew Drop - February 27, 2017 (#2430) - Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: