#1,095 – Creating and Using a Custom Command

While WPF provides a number of predefined routed commands that you can use, it can also be useful to define your own command to use in your application.

We start by defining an instance of a RoutedCommand, in this case defined as a static member of our main Window class.  We also define code for the CanExecute and Executed events that will perform the logic that we bind the command to.

    public partial class MainWindow : Window
        public MainWindow()
            this.DataContext = this;

        public static RoutedCommand GreetUserCommand = new RoutedCommand();

        private void GreetUser_CanExecute(object sender, CanExecuteRoutedEventArgs e)
            e.CanExecute = true;

        private void GreetUser_Executed(object sender, ExecutedRoutedEventArgs e)
            MessageBox.Show("Howdy howdy I'm a cowboy");

We can now set up a command binding from XAML and set the Command property for controls that should execute our command.

<Window x:Class="WpfApplication1.MainWindow"
        Title="Commands" Width="320" Height="220">

        <CommandBinding Command="{x:Static loc:MainWindow.GreetUserCommand}"

            <MenuItem Command="{x:Static loc:MainWindow.GreetUserCommand}"
                          Header="Say Howdy"/>

        <Button Content="Howdy" HorizontalAlignment="Center"
                Padding="10,5" Margin="10"
                Command="{x:Static loc:MainWindow.GreetUserCommand}"/>

We now have a command that executes when we click a button or a menu item in a context menu.