Executing a command from an event of your choice

To follow up on a previous post, I’m going to describe how to execute a command from any event raised by a graphical control. For this, I’ll leverage the MVVM pattern as well as the Expression Blend SDK (freely available here). The SDK provides behaviors (triggers and actions) that allow even further loosening between view and viewmodel. In particular, the InvokeCommandAction gives the designer the necessary flexibility to associate the controls of his choice to the execution of a command, without requiring the intervention of a developer.

The provided example solution requires WPF4 or Silverlight 4.

The procedure is as follows:

  • In the viewmodel, initialize and expose a property of type ICommand

    public DelegateCommand<string> MyCommand { get; set; }


    public ViewModel()


    this.MyCommand = new DelegateCommand<string>(MyCommand_Execute);



    void MyCommand_Execute(string text)



  • Make sure your project references the following assemblies from the Blend SDK :
    • System.Windows.Interactivity
    • Microsoft.Expression.Interactions
  • On the control you want to be used to execute the command, combine an EventTrigger with an InvokeCommandAction.In the accompanying project, the ValueChanged event of the slider triggers the InvokeCommandAction which is bound to the viewmodel’s MyCommand property.




           <i:EventTrigger EventName="ValueChanged">


    Command="{Binding MyCommand}"

    CommandParameter="{Binding Text, ElementName=textBox}"/>




Please note that the Expression Blend SDK features many other actions and triggers, and that it is very easy for your to develop your own extensions.

From Expression Blend

Fortunate Blend users will be happy to know that they will not even need a keyboard to associate an event to a command :

  • Open the view, and the toolbar. Look for InvokeCommandAction (in the Behaviors section)
  • Drag & drop InvokeCommandAction on the slider, so that the action appears below it in the object tree
  • Select the action, and in the Properties tab select:
    • The triggering event (EventName=ValueChanged)
    • The command, which is in the Data Context, selectable from the Data bind icon
    • The command parameter, also available for data binding from the square. In the example, the parameter is the Text property of the TextBox 
    • And that’s about it!