March 26, 2012

Custom commands with standard menus

Define the command:
public static class CustomCommands
{
    private static RoutedCommand exitCommand;

    static CustomCommands()
    {
        exitCommand = new RoutedCommand("ExitApplication", typeof(CustomCommands));
    }

    public static RoutedCommand Exit
    {
        get
        {
            return (exitCommand);
        }
    }

}
Define the command in the window bindings:
<Window.CommandBindings>
        <CommandBinding
          Command="{x:Static local:CustomCommands.Exit}"
    Executed="Exit_Execute" 
          CanExecute="Exit_CanExecute" />
    </Window.CommandBindings>
Of course you'll have to define the namespace in the window/page class node:
<Window ...
xmlns:local="clr-namespace:MyNamespace"
... >
Alternatively, define the command in the window constructor:
InitializeComponent();
...
   CommandBindings.Add(
    new CommandBinding(
   CustomCommands.Exit, // this is the command object
   Exit_Execute,      // execute
   Exit_CanExecute));// can it execute?
Define the menu item that will call the command
<MenuItem Header="E_xit" Command="local:CustomCommands.Exit" />
Now define the event handlers that will execute the command
private void Exit_Execute(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

private void Exit_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = CanExitApplication();
    e.Handled = true;
}

No comments: