Lectures on WPF
Commands

This lecture is based on the books of Nathan&Lehenbauer and MacDonald:

Why Commands ?

Small programs call their functionality directly via their event handlers, but sophisticated programs should code it separately from the event handlers in functional tasks and insert an intermediary level between the event handlers and the functional tasks.
Commands or more precisely Routed Commands serve as such an intermediary layer separating design from logic what means separating the work of user interface designers from the work of software developers.
It frees the designer to give user friendly names to as many UIElements as he wants and to call the same software from many different places of the user interface, the keyboard and from the internet.
The independent software developer can give his preferred names to the event handlers and to its tasks independently to how the user interface looks.Routed Commands bind the user interface to the software and help to resolve the usual conflicts, when the user isn't allowed to click all buttons at once.
The benefits of the intermediary routed command level are:
1. It keeps track of state of the task (executable or not?)
2. It informs any involved UI element to enable, disable, appear or hide to stay synchronized with the state of the task by firing and managing CanExecuteChanged-events = Command Routing.
3. It bundles and delegates several UI elements and keyboard inputs to a task.

All prefabricated commands that WPF offers have no functionality of their own. They are empty hulls that can be filled with arbitrary event handlers.
They just provide a name and some short-cut-keys but nothing else.
There are 4 libraries containing about 100 ready to use command objects:

Sample 1

This tiny sample demonstrates how a MenuItem and a Button and the keys Ctrl+N trigger the same ApplicationCommands.New.
The following "New"-Command event handler NewOnExecute starts nothing but a MessageBox.

Sample 2

This sample demonstrates how a MenuItem and a Button and the keys Ctrl+N trigger the ApplicationCommands.New, whereas a second Button switches the ApplicationCommands.New-sources on and off via an ApplicationCommands.NotACommand.

Sample 3

This sample lets you copy images and texts into the clipboard and reload them from the clipboard. Its most interesting part is the PasteCanExecute-function. It automatically switches off those Paste-buttons that cannot handle the current clipboard content.
Experiment: Try out this program by loading text and images from arbitrary other programs into the clipboard. Whenever you will return to this program, only those Paste-buttons will work that fit to the foreign clipboard content.