arolson101
arolson101

Reputation: 1502

In WPF how can I forward a Command to a child control?

I've got a MVVM-like situation (not using any frameworks) where I have a main window with a toolbar and a documents area. The documents have command bindings (e.g. Undo and Redo). When the keyboard focus is outside of the document, it doesn't know how to execute any of the commands, so the buttons become disabled.

What I would like to do is add a mechanism whereby the main window will forward commands to the active document (if it has one). Using CommandManager.AddPreviewCanExecuteHandler I can get the events in the main window, but I can't figure out how to send them on to the child document- I tried e.CanExecute = e.Command.CanExecute(CurrentDocument), but that just ends up re-calling the PreviewCanExecuteHandler again, and the child's CanExecute handler isn't called.

How can I send an arbitrary ICommand to a child control?

Upvotes: 3

Views: 2149

Answers (2)

arolson101
arolson101

Reputation: 1502

The answer is here- call CurrentDocument.RaiseEvent(e), making sure to do it via a handler registered with CommandManager.AddCanExecuteHandler (not AddPreviewCanExecuteHandler). And make sure to check for infinite recursion.

Upvotes: 1

Jay
Jay

Reputation: 57919

Presumably, you have some mechanism of managing active documents -- enumerating them, identifying the active document, etc.

I suggest that instead of thinking about taking commands from the main window and forwarding them to the document, think of it as taking the commands available on the active document and attaching them to the main window.

Whatever is your common interface among documents, add some properties:

ICommand Undo { get; }
ICommand Redo { get; }

Now you'll bind your main window's controls to ActiveDocument.Undo and ActiveDocument.Redo, where ActiveDocument is a property in your main window viewmodel. When ActiveDocument changes, you'll get a property change notification so the buttons can become enabled/disabled accordingly.

Incidentally, when I've done similar, I expose some composite object of which the ICommands are properties, but with separate CanUndo/CanRedo boolean properties and other metadata -- that gives me a nicer abstraction by which to control enabling and disabling based on the state of the commands stacks.

Upvotes: 0

Related Questions