I found actually 2 ways to handle mouse events on controls with the mvvm pattern.
Both ways are actually 1 way:
MVVM Light Toolkit by http://mvvmlight.codeplex.com/
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand
Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding SelectedItems,
ElementName=MyDataGrid}" />
</i:EventTrigger>
</i:Interaction.Triggers>
and the Blend interactivity.dll with Behaviours
<i:Interaction.Triggers>
<i:EventTrigger EventName=”MouseLeftButtonDown”>
<Behaviours:ExecuteCommandAction Command=”{Binding MyCommand}” CommandParameter=”{Binding MyCommandParameter}”/>
</i:EventTrigger>
</i:Interaction.Triggers>
Do you know of any better method?
Moderator: Why the heck are my last 6 xaml lines of code not visible at all? They are swallowed by IE and Iron browser. Would you please report the admin to fix that code script? its not working at all very often. prove: http://img251.imageshack.us/img251/5236/errorxt.png
Those are both good ways to do it if you need to handle MouseDown in arbitrary places.
However these situations generally are few and far between. Usually there is a simpler way:
There are many other examples of this. In fact, it is uncommon to find a situation in which a MouseDown maps to a Command and there isn't a cleaner way to do the same thing.
There is always another option. You can handle WPF events in the code-behind of the View and call the appropriate method on the ViewModel. The MVVM pattern doesn't forbid to write any code in the code-behind file of the View.
The ViewModel sample application of the WPF Application Framework (WAF) shows how this can work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With