Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling MouseLeftButtonDown in MVVM

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?

like image 517
Kuntady Nithesh Avatar asked Feb 18 '23 23:02

Kuntady Nithesh


1 Answers

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.

like image 175
Blachshma Avatar answered Feb 28 '23 01:02

Blachshma