#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.

        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Purple"/>
            <Setter Property="FontStyle" Value="Italic"/>

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


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"/>
<TextBlock Text="Siegfried" Style="{StaticResource BlueBig}"/>

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}"/>


#1,199 – Complete WPF Command Example

Below is a cheat sheet for creating a custom command in WPF.

Use a static property to expose a command object from the ViewModel or code-behind. RoutedUICommand allows for associating control text with the command itself.

private static RoutedUICommand _pressMeCommand = 
    new RoutedUICommand("Press Me", "PressMe", typeof(MainWindow));
public static RoutedUICommand PressMeCommand
    get { return _pressMeCommand; }

Add command handlers (in code-behind or ViewModel).

private void PressMe_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    e.CanExecute = CowboyCanTalk;
private void PressMe_Executed(object sender, ExecutedRoutedEventArgs e)
    MessageBox.Show("Howdy howdy I'm a cowboy");

Bind the command to its handlers, done here in XAML for a window.

    <CommandBinding Command="local:MainWindow.PressMeCommand" 

Wire a button up to the command. Note use of command’s Text property for the button’s Content (text).

<Button Command="local:MainWindow.PressMeCommand" 
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />

We can also wire up the command to other GUI elements, e.g. a menu item in a context menu. The menu item’s text is set up automatically.

        <MenuItem Command="{x:Static local:MainWindow.PressMeCommand}" />