MouseDragElementBehavior

Since I have some Silverlight 2 projects in development and Silverlight 3 is up and running I decided to upgrade some of the projects to Silverlight 3.

While doing this I decided to use some of the new features that Silverlight 3 has.

One of this is the MouseDragElementBehavior which is making my work a lot more easy if I what to make a draggble control.

Since I’ve searched the internet for a simple and clear example with now many results I’ve decided to make a simple example to demonstrate and understand how this works.

How to make a element or control draggble?

  1. First you add the control or element to the Silverlight LayoutRoot
  2. You just drag the MouseDragElementBehavior from the Assets panel from the Behaviors category to the element you what to drag.
  3. You Run the project.

Now while experimenting this the first control that pop in to my mind was the Button.

After adding the button to the LayouRoot and adding the behavior I was expecting it to work but it didn’t, so I’ve made a little work around this.

The button could not be draggble because the button is catching the mouse event while you click on it.

So one simple way to avoid this is to insert the Button in a container like a Canvas and make the container draggble.

In this case you just add a Canvas add the Button or if you already have the button use the Group Into function. To be able to select the container with the mouse you must leave a space between the button and the container margin, like I did (see the grey area).

Button in the container

clip_image001

 

 

 

Screen clipping taken: 25.07.2009; 5:36

clip_image002

Screen clipping taken: 25.07.2009; 5:39

clip_image003

Screen clipping taken: 25.07.2009; 5:36

Adding the behavior to the control.

clip_image004

Screen clipping taken: 25.07.2009; 5:37

And one more thing.

You can always limit the area of the drag element to his container by setting

ConstrainToParentBounds="True";

contraintdrag

    Here is the source :

     SL3_MouseDragElementBehavior_Example.rar

    Here is the live example:

    http://silverlight.services.live.com/invoke/104873/SL3_MouseDragElementBehavior_Example/iframe.html

    Hope this is useful.

    About these ads
    1. Leave a comment

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.

    %d bloggers like this: