#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

Advertisement

#312 – Specify a Default Button in a Window

You can use the IsDefault property to specify that a particular button in a window is the default button.  You can still click on the button like you would any other button in the window, but if you press the ENTER key, the default button will respond as if it was clicked.  The button responds to the ENTER key, no matter which control currently has keyboard focus.

        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <Button Content="Save" Width="100" Margin="10,20,10,20"
                    IsDefault="True"
                    Click="Save_Click"/>
            <Button Content="Cancel" Width="100" Margin="10,20,10,20"
                    Click="Cancel_Click"/>
        </StackPanel>

.