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:
public DelegateCommand<string> MyCommand { get; set; }
public ViewModel()
{
this.MyCommand = new DelegateCommand<string>(MyCommand_Execute);
}
void MyCommand_Execute(string text)
…
…xmlns:i=http://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.
Fortunate Blend users will be happy to know that they will not even need a keyboard to associate an event to a command :