Tag Archives: mvvm wpf mvvmlight interactivity

Binding WPF Events to MVVM ViewModel Commands

This article looks at binding event on WPF controls to commands in your MVVM view model.

A lot of MVVM examples show you how to bind a command in a view to an ICommand in your view model. What they sometimes skirt over, is how you get events into the view model. Prism for example recommends the use of an Event Aggregator.

However, there is an easier way! All we need is a class library that is part of Expression Blend. It’s called System.Windows.Interactivity and you can get hold of it from a variety of sources, but the one I recommend is the MVVM Light library.

This gives you the ability to create a trigger on an event and bind it to an ICommand on the view model.

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter" >
            <i:InvokeCommandAction Command="{Binding FooCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Assuming the DataContext is your view model, then the above will map the ‘MouseEnter’ event to ‘FooCommand’ on the view model.

The only issue here, is that InvokeCommandAction doesn’t give you the event parameters.

I’ve already mentioned MVVM Light, and this library provides the a solution, by offering a different event to command behaviour that can optionally pass the parameters. Like this:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter" >
             <cmd:EventToCommand Command="{Binding FooCommand}"
                 PassEventArgsToCommand="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

With this, you’ll find the MouseEventArgs in the Object passed into your command.