Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Mouse events on controls with MVVM pattern - best practice -

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

like image 583
msfanboy Avatar asked Jun 22 '10 08:06

msfanboy


2 Answers

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:

  • Are you sure your objects aren't really buttons that just don't look like buttons? If so, make them real Button objects and template them to look the way you want.
  • Are you sure your objects are just selection areas for objects in a list? If so, change the container from ItemsControl to ListBox and restyle ListBoxItem to use the selection areas.
  • Are your objects graphical paths that are being selected? Use a ToggleButton whose content is the path itself.

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.

like image 55
Ray Burns Avatar answered Nov 16 '22 10:11

Ray Burns


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.

like image 30
jbe Avatar answered Nov 16 '22 10:11

jbe