Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thumb Drag in MVVM, WPF, C#

I have one working app writen in C# WPF. I like to practice working with MVVM so I like to write same app as MVVM. But I came to a problem. There in my app I use

<Thumb DragDelta="Thumb_Drag" 
       DragStarted="Thumb_DragStarted"
       DragCompleted="Thumb_DragCompleted"
       ...

How I write this "Drag&Drop/Draggable" example in MVVM? I use "binding" or something else? Any example will be very welcome :) Thanks!

If dont understand please ask me.

like image 661
esispaned Avatar asked Mar 16 '23 08:03

esispaned


2 Answers

It's possible to use System.Windows.Interactivitylibrary which can be added as a reference in your project.

Add the namespace:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

And call commands through <i:InvokeCommandAction>:

<Thumb>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="DragDelta">
            <i:InvokeCommandAction Command="{Binding DataContext.ThumbDragDeltaCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Thumb>

ViewModel:

private ICommand ThumbDragDeltaCommand { get; set;}

public MainViewModel() //Constructor
{
    ThumbDragDeltaCommand = new DelegateCommand(x => 
    {
        //EventHandler
        //Do stuff...
    }
}

You can, however, still handle the event in your code-behind while still being committed to the MVVM-pattern as long as the events only trigger graphical changes.

like image 75
Hjalmar Z Avatar answered Mar 24 '23 03:03

Hjalmar Z


Depending on what kind of logic you have in those event-handlers I wouldn't see a problem in having them in the code-behind. After all MVVM is just a general guideline rather than a strict rule.
If you do insist on implementing them in a view-model you could add a reference to the System.Windows.Interactivity dll and use an InvokeCommandAction with an Interaction.Trigger.

<Thumb>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Thumb_Drag" >
            <i:InvokeCommandAction Command="{Binding SomeViewModelCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Thumb>
like image 25
user2697817 Avatar answered Mar 24 '23 03:03

user2697817