O'Reilly logo

WPF Programmer's Reference: Windows Presentation Foundation with C# 2010 and .NET 4 by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 19. Commanding

Many applications provide several ways to perform the same function. For example, in many applications you can copy the text selected in a textbox by any of the following actions:

  • Press [Ctrl]+C.

  • Right-click on the textbox and select the context menu's Copy command.

  • Open the Edit menu and select Copy.

  • Click the Copy button on the toolbar.

In all of these cases, the program performs the same action and copies the selected text.

Rather than using different pieces of code to perform the same action for each of these input scenarios, a well-designed application calls the same code for each. That reduces repeated code, so it means less code to write, debug, and maintain.

WPF formalizes this idea of providing centralized actions with commanding. Commanding separates the logical intent of an action (such as copying text) from the code that implements it.

Figure 19-1 shows three different approaches to handling text copying. In the bad design on the left, different input actions invoke different pieces of code. This design is bad because it contains several copies of the same code, making it harder to debug and maintain the code.

In the design in the middle, all of the input methods invoke the same piece of code. This design is better because all of the text copying code is stored in a central routine where it's easy to debug, modify, and maintain.

The design on the right illustrates commanding. All of the input methods invoke the same command object, which, in turn, calls ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required