简体   繁体   中英

Detect and handle Gestures in WP8 using MVVMLight

Problem

I'm currently trying to find a MVVMLight compatible way to use gestures in my WP8 app. Specifically I just want to detect a swipe/flick and bind it to a RelayCommand in my view model. Has there been any recent solution developed over the years that I'm unaware of?

Prior Research

I've done some research before hand, and the results I've come up with are mostly outdated or no longer exist. ie:

  1. Old Stackoverflow Question
  2. Clarity Consulting Blog Post with non-existant code
  3. toolkit:GestureListener from the Windows Phone Toolkit supports gestures but requires you to couple the ViewModel with the View.

Edit

Note: Found out that toolkit:GestureListener has been deprecated.

Joost Van Schaaik created such a behaviour on wp7: http://dotnetbyexample.blogspot.be/2011/03/simple-windows-phone-7-silverlight.html

He can be contacted on twitter by @localjoost

Found the answer to my question.

Instead of using toolkit:GestureListener , I found out that EventToCommand with ManipulationDelta or ManipulationCompleted works as well:

In XAML

<i:Interaction.Triggers>
    <i:EventTrigger EventName="ManipulationDelta">
    <Command:EventToCommand Command="{Binding SlideOutDeltaCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>
    </i:EventTrigger>
        <i:EventTrigger EventName="ManipulationCompleted">
    <Command:EventToCommand Command="{Binding SlideOutCompletedCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>
        </i:EventTrigger>
</i:Interaction.Triggers>

By passing in EventArgs to the ViewModel, you can detect whether a swipe gesture has been issued:

In ViewModel

Define RelayCommand

 public RelayCommand<ManipulationDeltaEventArgs> SlideOutDeltaCommand
    {
        get;
        private set;
    }

Define Execute() Method

 private void OnSlideDelta(ManipulationDeltaEventArgs e)
    {
        var delta = e.CumulativeManipulation.Translation;

        //If Change in X > Change in Y, its considered a horizontal swipe
        var isDeltaHorizontal = Math.Abs(delta.X) > Math.Abs(delta.Y) ? true : false;
    }

Register your Command in ViewModel Constructor

public MainViewModel()
{
    SlideOutDeltaCommand = new RelayCommand<ManipulationDeltaEventArgs>((e) => OnSlideDelta(e));
}

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