Using TouchPanel for Gestures in Windows Phone 7

The Silverlight for Windows Phone Toolkit has some excellent controls, one of which is the GestureListener which makes implementing gesture support a very straightforward task.   However, as happens from time to time you’re hit with a scenario where you’re unable to depend on any third party content and as such I needed to add my own basic handling for gestures.  This is how you do it:

1. Add reference to Microsoft.Xna.Framework.Input.Touch.dll – Note: you will get a warning here that you can ignore for now.

2. In code behind  the gestures you want to listen for

The Gesture types you can enable are as follows Tap, DoubleTap, Hold, HorizontalDrag, VerticalDrag, FreeDrag, Pinch, Flick, DragComplete, PinchComplete

In my case I only want to deal with Flick, Hold and Tap therefore add the following:
TouchPanel.EnabledGestures = GestureType.Flick | GestureType.Hold | GestureType.Tap;

3. Limiting the scope for the gestures.

I want the gestures to be captured only when performed in a given for a StackPanel.  To do this I handle the ManipulationCompleted event on the StackPanel as follows:

<StackPanel ManipulationCompleted="StackPanel_ManipulationCompleted">



Note: if you wanted the gesture available to the content of the whole page then you would handle the ManipulationCompleted event of the PhoneApplicationPage.

4. Add handling code as follows

private void StackPanel_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
   //Check if touch Gesture is available
   if (TouchPanel.IsGestureAvailable)
      // Read the gesture so that you can handle the gesture type
      GestureSample gesture = TouchPanel.ReadGesture();
      switch (gesture.GestureType)
         case GestureType.Flick:
         case GestureType.Hold:
         case GestureType.Tap:
            //do something