Tuesday, December 9, 2008

Composite WPF Guidance – Part 6 (Commands)

In a composite WPF application actions within the view are routed to the appropriate handlers outside of the view by using delegation and composition. WPF-routed commands deliver command messages through UI elements in the tree, but the elements outside the tree will not receive these messages because they only bubble up or down from the focused element or an explicitly stated target element. Additionally, the WPF-routed commands require a command handler in the code behind.
Use of Delegation and Composition overcomes this issue.
In delegation a command is used that delegates off its handling logic, either through events or delegates where it can be handled externally by a class such as a presenter, service, controller, and so on. This provides the benefit of not having to put any code in the code behind. The command requires two handlers: one for the Execute method and one for the CanExecute method. Whenever the Execute or CanExecute methods are called on the command, the handlers are called either through the event being raised or the delegate being invoked.
The DelegateCommand in CAL allows delegating the commanding logic instead of requiring a handler in the code behind. It uses a delegate as the method of invoking a target handling method.

The DelegateCommand uses its delegate to invoke a CanExecute method or Execute method on the target object when the command is invoked.

A composite command delegates off its handling logic to a set of child commands. The composite command needs to provide a way for the child commands to be registered. Executing the composite command executes the children. The composite commands CanExecute returns false, unless all the children return true. The CompositeCommand class contains a RegisterCommand method to register the child commands.

The figure below shows the relationship between a CompositeCommand and DelegateCommand.

No comments: