Building a Simple Windows Phone App - Page 3
       by kirupa  |  10 May 2010

In the previous page, you added a rectangle and customized how it looks. In this page, let's make this rectangle draggable!

Making the Rectangle Draggable
Traditionally, adding interactivity to your applications goes hand-in-hand with writing some code. Since this tutorial is all about breaking tradition, you can avoid writing code by using what are known as behaviors.

Behaviors are basically little pieces of interactivity that you attach to an element. Once a behavior has been attached, the element will now gain the magical superpowers the particular behavior exhibits.

Note - Optional Further Reading  
To learn more about behaviors, check out my earlier Introduction to Behaviors tutorial.

To save you some time from searching for a behavior or writing your own, for a handful of common scenarios, Expression Blend ships with some behaviors that you can use out of the box. One of the behaviors provided even helps you drag an element around, and that behavior is what you will use to make your rectangle draggable.

First, we need to find this behavior. Make sure your rectangle is selected, click on the Assets tab, and select the Behaviors node. You will see some behaviors displayed:

[ display all of the built-in behaviors ]

From the list of behaviors displayed, drag and drop the behavior called MouseDragElementBehavior onto your rectangle:

[ to apply a behavior, drag and drop it onto the element directory ]

Once you have dropped this behavior onto the rectangle, you'll see it displayed on your Objects and Timeline nested directly under your rectangle element:

[ applied behaviors show up in the Objects and Timeline panel ]

Your Properties Inspector will also display any properties this behavior exposes. We aren't going to worry about tweaking this behavior beyond what is automatically set for you.

Simply hit F5 to preview what you have so far. When you hit F5, you will see the Change Device Selection dialog appear:

[ choose between previewing in the emulator or on the device ]

Select the Windows Phone 7 Emulator option and and hit OK. After a few moments where your Windows Phone image gets fully loaded, you will see your application displayed:

[ your application running on the emulator ]

Notice that your rectangle is visible. Beyond just the looks, press down on the rectangle and drag the mouse around. Thanks to the MouseDragElement behavior, your rectangle follows your mouse cursor around the application.

Ok, now seems like a good time to take a quick break. In the next page, we'll create the animation that will snap your rectangle back to its original position.

Onwards to the next page

  1 | 2 | 3 | 4 | 5 | 6

SUPPORTERS:'s fast and reliable hosting provided by Media Temple.