The GoF Command design pattern is defined as "encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations". WPF Commands provide methods for decoupling UI events, the handling of these events and the registration of UI elements interested in handling the events.
WPF Commands are really very much like events but they offer some advantages:
- Reuse – Commands can be registered with multiple controls allowing for reuse.
- Routing – Commands based on the RoutedCommand base class can participate in event bubbling.
- XAML integration – Commands can be defined and registered with controls in XAML.
- Input gestures – There are a stack of build-in commands which are already configured to handle input gestures (e.g. using ApplicationCommands.Paste, a RoutedUICommand, will give you all Ctrl-V etc. out of the box).
- Testability – Commands can be tested.
- Localisation – Commands can be localised (which is done for you with built-in commands).
All WPF commands must implement a simple interface, ICommand:
public interface ICommand { // Methods. void Execute(object parameter); bool CanExecute(object parameter); // Events. event EventHandler CanExecuteChanged; }
- Execute - contains the logic to perform the action that makes up the command
- CanExecute - returns a value that determines if the command is currently valid
- CanExecuteChanged event - raised when the value returned by the CanExecute method has changed
Built-in commands take advantage of CanExecute and CanExecuteChanged to enable/disable functionality for you (i.e. registered controls’ will automatically become enabled/disabled appropriately).
See http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wpf_commandpattern.mspx
See http://msdn.microsoft.com/en-us/library/ms752308.aspx
More to follow on this one…