WPF Multi Target routed command
Although the command pattern is many to many, transactions normally involve one source and one receiver. The implementation of the pattern in WPF, for routed commands, strictly enforces this.
Under the hood, WPF uses routed events to implement routed commands. The
CommandManager class registers four
As per the norm with routed events, these are static members that are passed a mutable, EventArgs parameter to propagate the instance state. The
Handled property of the EventArgs class is set by the event handler if it needs to stop propagation of the event. The event handler for routed events resides in the
CommandBinding object, for example, the Executed handler looks like this...
The two things to notice are that:
- It will not execute if Handled is true
- It sets Handled to true after executing
This is why there can only be one target or receiver for a routed command transaction.
Multi Target Command
The objective is to create a library of custom controls that allow the consumer to compose multiple target commands in xaml as per the following example…
The elements required to support this are:
Implements ICommandSource, including a standard ICommand member, but extends the logical tree to support binding for child elements within the Command object.
Implements ICommand but presents a collection object with bindable elements for multiple command targets.
Standard RoutedCommands registered on the command manager.
- Custom Command Bindings
CommandBindingbut with built-in handlers so that the receiver can be applied to any qualified, standard element by composition, in xaml.
Binding and the logical tree
Binding in WPF
DependencyObjects relies propagation of context throughout the logical structure of the View. To do this, the relationship between elements needs to be established and the platform for this is the logical and visual trees in WPF. In order to extend binding capability to custom child elements, they need to be incorporated into this structure so that the binding system can establish the context for their bindings. This happens naturally when adding
FrameworkElements but the command property that we need to host extra child elements is not a dependency property and that can’t be changed, so we need another way to manage delivery of binding context.
Adopting logical children
The infrastructure for managing the trees is provided by