简体   繁体   中英

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.

It's possible to use System.Windows.Interactivity library 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM