Kiang Teng
Kiang Teng

Reputation: 1705

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. i.e:

  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.

Upvotes: 0

Views: 675

Answers (2)

Kiang Teng
Kiang Teng

Reputation: 1705

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));
}

Upvotes: 0

Depechie
Depechie

Reputation: 6142

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

Upvotes: 1

Related Questions