Search code examples
c#.netxamlwindows-runtimewindows-store

Handle Swipe Up, Swipe Down, Swipe Left & Swipe Right Gestures in a WinRT app


I have the following code:

public MainPage()
{
    this.InitializeComponent();
    this.ManipulationStarting += MainPage_ManipulationStarting;
    this.ManipulationStarted += MainPage_ManipulationStarted;
    this.ManipulationInertiaStarting += MainPage_ManipulationInertiaStarting;
    this.ManipulationDelta += MainPage_ManipulationDelta;
    this.ManipulationCompleted += MainPage_ManipulationCompleted;
}
void MainPage_ManipulationStarting(object sender, ManipulationStartingRoutedEventArgs e)
{
    Debug.WriteLine("MainPage_ManipulationStarting");
}
void MainPage_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
    Debug.WriteLine("MainPage_ManipulationStarted");
}
void MainPage_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
{
    Debug.WriteLine("MainPage_ManipulationInertiaStarting");
}
void MainPage_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    Debug.WriteLine("MainPage_ManipulationDelta");
}
void MainPage_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
    Debug.WriteLine("MainPage_ManipulationCompleted");
}

But I have no idea on how to use the Manipulation events. Can you anyone describe how to handle the gestures swipe up, down, left and right?


Solution

  • Manipulation events provide you the translation values. Manipulation Delta will fire continuously until your manipulation completed along with inertia. In this event check whether the move is inertial, (a normal move shouldn't be considered as swipe) and detect the difference between initial and current position.

    Once it reached the threshold, fire the swipe up/down/left/right event. And stop the manipulation immediately to avoid firing the same event again and again.

    Following code will help you,

        private Point initialpoint;
    
        private void Grid_ManipulationStarted_1(object sender, ManipulationStartedRoutedEventArgs e)
        {
            initialpoint = e.Position;
        }
    
        private void Grid_ManipulationDelta_1(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            if (e.IsInertial)
            {
                Point currentpoint = e.Position;
                if (currentpoint.X - initialpoint.X >= 500)//500 is the threshold value, where you want to trigger the swipe right event
                {
                    System.Diagnostics.Debug.WriteLine("Swipe Right");
                    e.Complete();
                }
            }
        }