Commands
The input events we've examined give us a detailed view of user input directed at individual elements. However, it is often helpful to focus on what the user wants our application to do, rather than how she asked us to do it. WPF supports this through the command abstraction—a command is an action the application performs at the user's request.
The way in which a command is invoked isn't usually important. Whether the user presses Ctrl-C, selects the Edit → Copy menu item, or clicks the Copy button on the toolbar, the application's response should be the same in each case: it should copy the current selection to the clipboard. The event system we examined earlier in this chapter regards these three types of input as being unrelated, but WPF's command system lets you treat them as different expressions of the same command.
The command system lets a UI element provide a single handler for
a command, reducing clutter and improving the clarity of your code. It
enables a more declarative style for UI elements; by associating a
MenuItem or Button with a particular command, you are
making a clearer statement of the intended behavior than you would by
wiring up Click event handlers. Example 4-15 illustrates how commands
can simplify things.
Example 4-15. Commands with a menu and text box
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_Edit">
<MenuItem Header="Cu_t" Command="ApplicationCommands.Cut" />
<MenuItem Header="_Copy" Command="ApplicationCommands.Copy" /> <MenuItem ...