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.

    …xmlns:i=https://schemas.microsoft.com/expression/2010/interactivity

    <Slider

           <i:Interaction.Triggers>

           <i:EventTrigger EventName="ValueChanged">

            <i:InvokeCommandAction

    Command="{Binding MyCommand}"

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

            </i:EventTrigger>

            </i:Interaction.Triggers>

    </Slider>

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)
    image_thumb3
  • Drag & drop InvokeCommandAction on the slider, so that the action appears below it in the object tree
    image_thumb5
  • Select the action, and in the Properties tab select:
    • The triggering event (EventName=ValueChanged)
      image_thumb7
    • The command, which is in the Data Context, selectable from the Data bind icon
      image_thumb8
      image_thumb10
    • The command parameter, also available for data binding from the square. In the example, the parameter is the Text property of the TextBox 
      image_thumb11image_thumb13
    • And that’s about it!

InvokeCommandActionDemo.zip