More on Commands, Input and the WPF - Enabling and disabling commands
(Page 2 of 4 )
As well as supporting execution of commands, CommandBinding objects can be used to determine whether a particular command is currently enabled. The binding raises a PreviewCanExecute andCanExecutepair of events, which tunnel and bubble in the same way as thePreviewExecutedandExecuted events. Example 4-26 shows how to handle this event for the system-definedRedocommand.
Example 4-26. Handling QueryEnabled
public Window1() {
InitializeComponent();
CommandBinding redoCommandBinding =
new CommandBinding(ApplicationCommands.Redo);
redoCommandBinding.CanExecute += RedoCommandCanExecute;
CommandBindings.Add(redoCommandBinding);
}
void RedoCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = myCustomUndoManager.CanRedo;
}
Command bindings rely on the bubbling nature of command routing—the top-level Window element is unlikely to be the target of the command, as the focus will usually belong to some child element inside the window. However, the command will bubble up to the top. This routing makes it easy to put the handling for commands in just one place. For the most part, command routing is pretty straightforward—it usually targets the element with the keyboard focus, and uses tunneling and bubbling much like normal events. However, there are certain scenarios where the behavior is a little more complex, so we will finish off with a more detailed look at how command routing works under the covers.
Next: Command routing >>
More .NET Articles
More By O'Reilly Media
|
This article is excerpted from Programming WPF, Second Edition, written by Chris Sells and Ian Griffiths (O'Reilly, 2007; ISBN: 0596510373). Check it out today at your favorite bookstore. Buy this book now.
|
|