Drag and drop Silverlight example

Posted by Corey on August 13, 2008 at 9:34 pm.

This is a quick and simple example of how to create a draggable object in Silverlight 2.

  1. Create a Rectangle and set the RenderTransform to a TranslateTransform.
  2. drag_drop_1

  3. Register the MouseLeftButtonDown, MouseLeftButtonUp, and the MoseMove events for the rectangle.
    drag_drop_2
  4. In the MouseLeftButtonDown and MouseLeftButtonUp event you will capture and release the capture of the mouse, respectively.  Also, you will need to store if the mouse is captured.
  5. drag_drop_3

  6. Finally, update the position if the mouse is captured and the mouse is moving.
  7. drag_drop_4

Final product:

image

Maintain mouse position on object while dragging

The above example snaps the pointer to the top left of the object.  Face it, it’s annoying, what you really want is the mouse to maintain the position on the element while dragging. To solve this problem is simple.

  1. Add a variable to save the position when the user clicks the object.
    drag_drop_5
  2. Save the position of where the mouse is located on the MouseLeftButtonDown event.  The updated MouseLeftButtonDown event looks like:
    drag_drop_6
  3. Finally, in MouseMove event subtract the clickPosition from the mouse position.
    drag_drop_7

Update

Drag and drop with physics (friction)

After playing around, I have updated this example to incorporate physics.  Take a look:

http://www.85turns.com/silverlight/drapDropPhysics.html

23 Responses to “Drag and drop Silverlight example”

Leave a Reply