Configure WPF commanding
May include but is not limited to: defining WPF commands based on RouteCommand; associating commands to controls; handling commands; command bindings; input gestures
To understand commands, I think the best way is to fire up, let’s say Word, and have a look around the UI and search for tasks. For example, when you’d like to undo something, you have a variety of choices: press Ctlr + Z, or right click to get a context menu, and click the undo command. You can even hit undo on the ribbon, and there are certainly various elements that you can call to get the same result done.
Of course, you can implement this functionality by using a switchboard-like code-behind class – you factor out the undo logic, and call it from a variety of event handlers. But what if you have an undo icon, and you can’t undo anything more. Then the icon should be disabled, doesn’t it? Here comes the WPF command system into picture.
A command in WPF is a class that implements the ICommand interface. This interface is quite simple, it has two methods and an event, as follows:
- CanExecute(object): returns a Boolean value indicating that the command can execute (there’s something still left on the undo queue).
- CanExecuteChanged: an event triggered when the execution state changed. This can be used to update (enable/disable) the UI.
- Execute(object): a void method to call when you trigger the command.
So you can see that the ICommand interface is quite simple. However, you’ll rarely need to implement it directly (it doesn’t even covered in the exam material). What you’ll use is the RoutedCommand class, and that’s what you will subclass to get a custom command. It also implements event bubbling for you.
To execute commands, you need a class that implements ICommandSource. You don’t have to write a class to do that, of course, because e. g. ButtonBase implements it, too. For example, to hook the undo command to a button, you’ll have to do this:
<Button Command=”Undo” Content=”Undo” />
And you have an undo command, but it won’t work, because first you’ll need a binding for it, which you can set up as this:
CommandBinding undoBinding = new CommandBinding(Undo);
undoBinding.Executed += Undo_Executed;
Now your command can work as you desired – of course the responsibility to set up the Undo_Executed method is yours!
You can even execute commands directly from code. One such example is as follows:
I think that this is a decent starting point for commands and for the exam as well. Next time we’ll have a look at the modification of the UI at run time!