5

My XAML is:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate>
            <Image Source="X.png" HorizontalAlignment="Left"
                                 Width="20" Height="20" 
                                 MouseLeftButtonDown="Image_MouseLeftButtonDown"/>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Now I am following MVVM. I need to change the code to make it work with ViewModel. How can I handle MouseLeftButtonDown event with ViewModel?

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Kuntady Nithesh
  • 11,371
  • 20
  • 63
  • 86
  • There nothing to do, you need code behind for left click. read it [WPF and MVVM. Binding Events][1] [1]: http://stackoverflow.com/questions/4785685/wpf-and-mvvm-binding-events – zzfima Jan 02 '13 at 05:49

2 Answers2

5

When working with MVVM: A trigger in the View (be it a MouseLeftDown, a MouseHover etc.) triggers a Command in the ViewModel.
These commands perform some operation in the ViewModel, and if this command changes any data which is binded in the view, you can see the results in the view.

Therefore don't ask "How can I handle MouseLeftButtonDown event with view model" rather decide what is it you want to do in the ViewModel (such as removing an item from a listbox, navigating to another view, refreshing the data etc...) and create a specific command for it.

The MouseLeftDown can trigger that command... But what exactly is done should not be part of the view...

Here is an example of catching a mouse event and running a command, using MVVM and only XAML.

Community
  • 1
  • 1
Blachshma
  • 17,097
  • 4
  • 58
  • 72
3

In my opinion, a left mouse button should not be handled by "MVVM" (handled by a binding). It has noting to do with the model, as it is relaetd to the UI experience.

I would attach to the "old fashioned" MouseRightButtonDown event in my codebehind for that, and then fire the command or method in the view. Because the model does not need to know HOW the command was executed. Button clicks, mouse gestures and menues is UI-related.

At least in my opinion :-)

Mats Magnem
  • 1,375
  • 1
  • 10
  • 21