Command in WPF – Custom Command – Command Binding


Commands in WPF  represent high-level tasks that are performed in the application. Paste is an example of a command; it represents the task of copying an object from the clipboard into a container

In past you would have to create different event handler for each menu, button, context menu to handle task like paste. Also code to deactivate control is task is not available.

Commands enable you to use a centralized architecture for tasks. You can associate any number of UI controls or input gestures with a command and bind that command to a handler that is executed when controls are activated or gestures are performed. Commands also keep track of whether they are available. If a command is disabled, UI elements associated with that command are disabled, too.

Four parts of command:

  1. Command object i.e. task to be performed
  2. Source of command i.e control that will raise command
  3. Command handler
  4. CommandBinding which keeps track of which control and command are bound together

Many WPF elements implement ICommandSource hence they invoke command bound to their command property automatically.

You also can register mouse and keyboard gestures with Command objects that invoke the command when those gestures occur

To execute command from code you can directly call Command.Execute and it will bubble up until command binding is not found.

private void myCommandHandler(object sender, ExecutedRoutedEventArgs e){

// Handle the command here }

ExecutedRoutedEventArgs is derived from RoutedEventArgs and thus exposes all the members RoutedEventArgs does. In addition, it exposes a Command property that returns the Command object being handled.

How to add command binding

  1. Create command binding object
  2. Attach command and handler to execute vent
  3. Add it to command bindings collection of window or control

How to disable command

You can write logic of command disabling in CanExecute method. It will be executed at various places in application lifetime. This can be done by attaching handler to CanExecute event of command.

Creating custom command:

Create a class and declare static command as private and initialize it in static constructor while giving getter only to outside world.

Leave a Reply

Your email address will not be published. Required fields are marked *