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.

Implementation details

Under the hood, WPF uses routed events to implement routed commands. The CommandManager class registers four RoutedEvents:

Executed, CanExecute, PreviewExecuted and PreviewCanExecute.

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...

In CommandBinding class

The two things to notice are that:

  1. It will not execute if Handled is true
  2. 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:

  1. MultiCommandSource
    Implements ICommandSource, including a standard ICommand member, but extends the logical tree to support binding for child elements within the Command object.
  2. MultiTargetCommand
    Implements ICommand but presents a collection object with bindable elements for multiple command targets.
  3. RoutedCommands
    Standard RoutedCommands registered on the command manager.
  4. Custom Command Bindings
    Derives from CommandBinding but 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 DependencyProperties to 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 FrameworkEelement,