Adding Swipe functionality to WPF Applications

As part of a kiosk application written in WPF, the client wanted ‘Swipe’-like functionality similar to many touch-enabled smartphones. It’s actually not that hard in .NET 4 and WPF. 

First, add a property to your page/control that keeps track of the Touch that the user has initiated to start the swipe event:

protected TouchPoint TouchStart;

In the codebehind of the Page or Control you’re building, add the following handlers:

 

public BasePage()

{

this.TouchDown += new EventHandler<TouchEventArgs>(BasePage_TouchDown);

this.TouchMove += new EventHandler<TouchEventArgs>(BasePage_TouchMove);            

}

These handlers help detect when a user has pressed down and moved his/her finger over your page or control.

Next, handle the initial Touch event that triggers the swipe:

 

void BasePage_TouchDown(object sender, TouchEventArgs e)

{            TouchStart = e.GetTouchPoint(this); }

Finally, handle the movement aspect of the touch. If the movement exceeds some threshhold; then we consider it a swipe and execute whatever code we want to do (Navigation, animation, etc)

Here, ‘AlreadySwiped’ is just a flag property so we don’t execute the same task multiple times if the swipe exceeds our threshhold more than once. You are responsible for resetting it after you do your on-swiped code. Also, I used 200 pixels as the swipe threshhold, but you may want a bigger/smaller value. You may also want to consider percentages of X here instead of actual pixels.

void BasePage_TouchMove(object sender, TouchEventArgs e)

{

            if (!AlreadySwiped)

            {                

                var Touch = e.GetTouchPoint(this);

                //right now a swipe is 200 pixels 

 

                //Swipe Left

                if (TouchStart != null && Touch.Position.X > (TouchStart.Position.X + 200))

                {

                    RunMyCustomCode();

                    AlreadySwiped = true;

                }

 

                //Swipe Right

                if (TouchStart != null && Touch.Position.X < (TouchStart.Position.X – 200))

                {

                     RunMyCustomCodeSwipeRight();

                    AlreadySwiped = true;

                }

            }

            e.Handled = true;

}

This should be straightforward but send me a message if you have any questions.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>