How to: Enable a Command
The following example demonstrates how to use commanding in Windows Presentation Foundation (WPF). The example shows how to associate a RoutedCommand to a Button, create a CommandBinding, and create the event handlers which implement the RoutedCommand. For more information on commanding, see the Commanding Overview.
Without the CommandBinding there is no command logic, only a mechanism to invoke the command. When the Button is clicked, the PreviewExecuted RoutedEvent is raised on the command target followed by the Executed RoutedEvent. These events traverse the element tree looking for a CommandBinding for that particular command. It is worth noting that because RoutedEvent tunnel and bubble through the element tree, care must be taken in where the CommandBinding is put. If the CommandBinding is on a sibling of the command target or another node that is not on the route of the RoutedEvent, the CommandBinding will not be accessed.
The Executed handler calls a method to close the open file. The CanExecute handler calls a method to determine whether a file is open. If a file is open, CanExecute is set to true; otherwise, it is set to false.