Windows Phone: Touch

Windows Phone From Scratch #48

A key gesture for Windows Phone users is the tap or touch on the screen.   touchMany controls have built-in support for the touch (e.g., the button) converting the touch to an existing click event.

Other controls, however, do not have such support. If you want to respond to a touch on a panel, for instance, you need to write that support for yourself. Happily, this turns out to be easy to do.  The recommended course of action is to associate the touch with the MouseLeftButtonDown, and naturally enough, the release of the touch with the MouseLeftButtonUp event, both found on the base class UIElement.

Writing these associations is not burdensome, but by creating a custom behavior you can write this once, and then apply it to any control you like, as often as you like.

To get started, create a new project named “Toucher.”  You’ll need a reference to System.Windows.Interactivity as well as a using statement for the same library.

Create a new class named TouchAction and have it inherit from Behavior<UIElement>

using System.Windows.Interactivity;

namespace Toucher
{
   public class TouchAction : Behavior<UIElement>
   {

   }
}

 

Like all behaviors, yours will want to have an event, which in this case we’ll name Touch.  We’ll track the status of the button with a boolean MouseDown and we’ll override botht he Attached and the OnAttached and OnDetaching() member methods, wiring up (and unwiring) event handlers for MouseLeftButtonDown and MouseLeftButtonUp.

 

namespace Toucher
{
   public class TouchAction : Behavior<UIElement>
   {
      public event EventHandler Touch;

      protected bool MouseDown { get; set; }

      protected override void OnAttached( )
      {
      }

      protected override void OnDetaching( )
      {
      }
   }
}

On MouseLeftButtonDown we’ll set the boolean value MouseDown to true. On MouseLeftButtonUp we’ll test the boolean and if it is true (indicating the touch was begun inside the panel) then we’ll fire off our event. In any case, MouseLeftButtonUp will set MouseDown to false.

private void AssociatedObject_MouseLeftButtonUp(
   object sender, MouseButtonEventArgs e )
{
   if ( MouseDown )
   {
      OnTouch( );
   }
   MouseDown = false;
}

private void OnTouch( )
{
   if ( Touch != null )
      Touch( AssociatedObject, EventArgs.Empty );
}

private void AssociatedObject_MouseLeftButtonDown(
   object sender, MouseButtonEventArgs e )
{
   MouseDown = true;
}

 

When the OnTouch is called, we make sure we have subscribers and then we raise the event, passing along the AssociatedObject (the object that has this behavior) and an empty set of EventArgs,

private void OnTouch( )
{
   if ( Touch != null )
      Touch( AssociatedObject, EventArgs.Empty )
}

 

Save the TouchAction class and build the project. Then reopen the project in ExpressionBlend and rebuild there.  This will make the action available in your list of Actions.

Add a panel, such as a Border, to your grid,

Drag your new behavior onto the Border element and set its name and its Touch event (or you can set the touch event handler programmatically).

<Border
   Background="Beige"
   HorizontalAlignment="Stretch"
   VerticalAlignment="Stretch"
   Margin="25"
   BorderBrush="White"
   BorderThickness="5">

   <Custom:Interaction.Behaviors>
      <local:TouchAction
         x:Name="TouchActionBehavior"
         Touch="TouchActionBehavior_Touch" />
   </Custom:Interaction.Behaviors>
</Border>

You are now ready to respond to the TouchActionBehavior in the TouchActionBehavior_Touch method in your code behind. Save your application and reopen it in Visual Studio. Open the code behind page and, for now, let’s just light up a message box,

 private void TouchActionBehavior_Touch(
    object sender, System.EventArgs e )
 {
    System.Windows.MessageBox.Show(
       "You touched the panel!" );
 }
Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
This entry was posted in Blend, Essentials, Mini-Tutorial, WindowsPhone and tagged , , . Bookmark the permalink.

4 Responses to Windows Phone: Touch

  1. holyfetzer says:

    You need to register your event handlers to the events:

    protected override void OnAttached()
    {
    base.OnAttached();
    AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
    AssociatedObject.MouseDown += AssociatedObject_MouseLeftDown;
    }

    protected override void OnDetaching()
    {
    base.OnAttached();
    AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
    AssociatedObject.MouseDown -= AssociatedObject_MouseLeftDown;
    }

    • holyfetzer says:

      Correction:

      protected override void OnDetaching()
      {
      base.OnDetaching();
      AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
      AssociatedObject.MouseDown -= AssociatedObject_MouseLeftDown;
      }

  2. rams says:

    hi! i tried out the above example. but for some reason, the event is not raising. as i don’t have a Windows Phone 7 hand device, am using WP7 Emulator. i guess it should work equally. any help in the issue is appreciated.

  3. Pingback: Touch in der Metro « Pocketmobile's Blog

Leave a Reply

Your email address will not be published.

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>