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

<Window.CommandBindings>
    <CommandBinding Command="local:MainWindow.PressMeCommand" 
                    CanExecute="PressMe_CanExecute" 
                    Executed="PressMe_Executed"/>
</Window.CommandBindings>

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.

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