Silverlight Commanding

.Silverlight Commanding



Overview

"Commanding allows events triggered in a view, such as a Button's Click event, to be routed directly to a ViewModel instance without having to add code in a code-behind file."

Limited support for commanding was introduced in Silverlight 4. It does not implement all the commanding that is available in WPF, but it does support commanding for the ButtonBase and Hyperlink classes. The idea behind commanding is to have a UI element (e.g. button) invoke a logical command directly, instead of invoking an event handler. The logical command can provide consistent usage in different contexts and across different applications. Examples of this type of usage is the CTRL-C key combination to copy an object. The logical command can also be used in the MVVM design pattern to bind the ViewModel directly to the UI, and not have events coded in the code-behind file.

  1. Commanding can be used used to provide a consistent command across applications and for different contexts (e.g. CTRL+C = Copy).
    • While the command is the same, the logic for performing the operation may be defined differently in the various applications and for different object types (text, image, Web browser).

    • Commanding can also allow multiple UI elements to fire the same command.
  2. Commanding is often associated with the Model-View-ViewModel (MVVM) design pattern.
    • Commanding allows events triggered in a View, such as a Button's Click event, to be routed directly to a ViewModel instance without having to add code in a code-behind file.

    • In the commanding system, you don't respond to a button's click event anymore; you are binding a command to the button and allowing any button to execute it directly from the UI layer.

    • Commanding is the process of forwarding events that occur in the user interface to a ViewModel object for processing at runtime. The RelayCommand class will be used to wire properties in a ViewModel to methods that are invoked when any control derived from ButtonBase is clicked in a View. It satisfies the ICommand interface allowing commanding to be used in Silverlight MVVM applications.
,Model-View-ViewModel


Model-View-ViewModel


ICommand Interface

  1. The ICommand Interface is at the center of the commanding system.
    • The ICommand Interface has two methods:
      1. CanExecute - returns true if the command is allowed to execute.

      2. Execute - defines the method to be called when the command is invoked.
    • The ICommand Interface has one event:
      1. CanExecuteChanged - event gets raised when the CanExecute property changes.



Reference Articles


Top