Articles in categories

Articles

Event to Command in MVVM

Here's how to bind a control's event to an MVVM command. You can use the 'System.Windows.Interactivity' dll that is a part of the Expression Blend SDK.

A simple example:

<ComboBox Name="comboBox1"
		   SelectedItem="{Binding SelectedItem,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
		   ItemsSource="{Binding ItemsList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="SelectionChanged">
			<i:InvokeCommandAction Command="{Binding MyVMCommand}" />
		</i:EventTrigger>
	</i:Interaction.Triggers>
</ComboBox>

 It's also possible to pass a parameter to the command. In this case I pass the ComboBox's SelectedItem to the command:

<ComboBox Name="comboBox1"
	  SelectedItem="{Binding MySelectedItem,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
	  ItemsSource="{Binding ItemsList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="SelectionChanged">
			<i:InvokeCommandAction Command="{Binding MyVMCommand}" 
							      CommandParameter="{Binding SelectedItem, ElementName=comboBox1}"/>
		</i:EventTrigger>
	</i:Interaction.Triggers>
</ComboBox> 

After you've added it to your project, you just need to include the 'System.Windows.Interactivity' dll into your XAML namespaces.

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

That assembly can be found in the  Expression Blend SDK which is a free download (it also gets installed with Expression Blend), or through the internet.

After you installed the Expression Blend SDK you can find it here:

For WPF:
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries

For Silverlight:
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries

However you can just download it here and include it into your project references.