March 26, 2012

Using Application Commands

Define the command binding
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
 Executed="CloseCommandHandler"
 CanExecute="Close_CanExecute"
 /> 
 ...
 </Window.CommandBindings> 
and then define the menu item:
<MenuItem Header="E_xit" Command="ApplicationCommands.Close" />
Again ensure that within the code behind window class that the event handlers are defined:
private void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
    e.Handled = true;
}

private void Close_Execute(object sender, ExecutedRoutedEventArgs e)
{
    DoClose();
}
Beware of using commands with Context Menus. There is a 'gotcha' here. This is explained here: How to Solve Execution Problems of RoutedCommands in a WPF ContextMenu The simplest solution is to call 'Focus()' on the parent window.

No comments: