WPF: Attaching Commands to RoutedEvents

A very common problem in WPF and especially MVVM is that Commands, that is classes that implement the ICommand interface can by default only be attached to instances of classes that implement the ICommandSource interface. Therefore, you can attach only to MenuItem and Button.

Often, we would like to execute logic that is encapsulated in a command from other places, such as when the user selects an item from a ComboBox or ListBox.

There are multiple ways to achieve this using an Attached Behavior. I find the easiest is to use the Interactivity classes from the System.Windows.Interactivity.dll assembly. The assembly belongs to Expression Blend and is shipped with Visual Studio. It contains classes that allow you to hook commands to RoutedEvents using only XAML. This is what you have to do:

1. Add an assembly reference to System.Windows.Interactivity.dll.
2. Add the namespace in your xaml file:

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

3. Use the Interaction Trigger class to attach to Events:

Attach to ComboBox.SelectionChanged:

<ComboBox Width="200" Height="30" >
      <sys:String>Item1</sys:String>
      <sys:String>Item2</sys:String>
      <sys:String>Item3</sys:String>
      <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                  <i:InvokeCommandAction Command="{Binding ShowMessageBoxCommand}" />
            </i:EventTrigger>
      </i:Interaction.Triggers>
</ComboBox>

Done!

The code example can be downloaded here: