Tuesday, January 31, 2012

WPF Commanding: The Basics

Commanding in WPF is unlike your traditional events in WinForms. Commands were primarily designed to be used at the application level, but they have become one of the most popular features among developers when it comes to UI programming (we tend to use them more than they should be). Commands enable the developer to define a task once and “attach” it multiple times without having to go through the traditional means which would require duplicating the code or even calling it in more than one place. (This is the magic.) WPF intrinsically provides five commands that you can use out of the box.

  1. ApplicationCommands
  2. ComponentCommands
  3. EditingCommands
  4. MediaCommands
  5. vNavigationCommands

I have explored them and have taken a liking to ApplicationCommands. (In fact this is the one that most developers will use.)

To use the command, do the following:

  1. Link your custom/predefined command to a control that you want to respond to the command and add an input gesture to the command.
  2. Create a handler for the command and use the CommandBindings class to bind the handler to the control.
  3. Add the binding to the control’s Commands collection.

So let’s delve into some code to demonstrate WPF commanding.

No comments:

Post a Comment