#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()
        {
            InitializeComponent();
            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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:loc="clr-namespace:WpfApplication1"
        Title="Commands" Width="320" Height="220">

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static loc:MainWindow.GreetUserCommand}"
                        CanExecute="GreetUser_CanExecute"
                        Executed="GreetUser_Executed"/>
    </Window.CommandBindings>

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

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

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

1095-001

1095-002

Advertisements