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




About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,095 – Creating and Using a Custom Command

  1. Pingback: Dew Drop – June 17, 2014 (#1799) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: