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
            return (exitCommand);

Define the command in the window bindings:
          Command="{x:Static local:CustomCommands.Exit}"
          CanExecute="Exit_CanExecute" />
Of course you'll have to define the namespace in the window/page class node:
<Window ...
... >
Alternatively, define the command in the window constructor:
    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)

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

No comments: