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 :