WPF Commands


WPF commands are closely related to events. When the user clicks a button, chooses something from a menu or uses a keyboard shortcut, all of those actions may result in exactly the same thing. It’s typical for a function to be reachable from several places. Each of these actions needs to perform what is typically the exact same piece of code. We have multiple entrances to the same function.

Over at WPF Tutorial they say: “Commands don’t actually do anything by themself. At the root, they consist of the ICommand interface, which only defines an event and two methods: Execute() and CanExecute(). The first one is for performing the actual action, while the second one is for determining whether the action is currently available. To perform the actual action of the command, you need a link between the command and your code and this is where the CommandBinding comes into play. A CommandBinding is usually defined on a Window or a UserControl, and holds a reference to the Command that it handles, as well as the actual event handlers for dealing with the Execute() and CanExecute() events of the Command.”

You can define your own commands, but there are over 100 commonly used commands that you can use, thanks to the WPF team at Microsoft.

Commands help you to respond to a common action from several different sources, using a single event handler.

A Very Simple Example

We’ll create a program that has two buttons. When the user clicks either button they get a simple message from a MessageBox.

Here is the code.

<Window x:Class="UsingCommands.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:UsingCommands"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="Using Commands" Height="100" Width="280">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed" 
                        CanExecute="NewCommand_CanExecute" />
        <CommandBinding Command="ApplicationCommands.Open" Executed="OpenCommand_Executed" 
                        CanExecute="OpenCommand_CanExecute" />
    </Window.CommandBindings>

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Command="ApplicationCommands.New" Margin="3">New</Button>
        <Button Command="ApplicationCommands.Open" Margin="3">Open</Button>
    </StackPanel>
</Window>

Below is the procedural code behind.

using System.Windows;
using System.Windows.Input;

namespace UsingCommands
{ 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void NewCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {   //we want this particular command to be available all the time, so set to true.
            e.CanExecute = true;
        }
        private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {   // This command has a default keyboard shortcut defined. 
            // Instead of clicking the button, you can try to press Ctrl+N on your keyboard
            MessageBox.Show("The New command was invoked");
        }
        private void OpenCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {   //we want this particular command to be available all the time, so set to true.
            e.CanExecute = true;
        }
        private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {   // This command has a default keyboard shortcut defined. 
            // Instead of clicking the button, you can try to press Ctrl+N on your keyboard
            MessageBox.Show("The Open command was invoked");
        }
    }
}