Drag and Drop Manager for Silverlight 2

October 29, 2008 11:50 by Rob

Preview

One thing that I found lacking in the current Silverlight distribution is the ability to quickly implement drag and drop. I have seen a couple of one-off implementations on the web, but they need a lot of coding every time drag and drop is required. So I came up with my own DragDrop toolkit.

For our drag-drop to work we need three components:

  1. The object to be dragged (one or more)
  2. The component that centralizes all drag and drop functionality
  3. The drop target (one or more).

For number one, I designed a Silverlight custom control that wraps around a FrameworkElement by inheriting from ContentControl. this control adds the drag possibility.

Number 2 is designed as a UI-less component that couples the drag with the drop. Since it is a container control, it also inherits from ControlControl

Number 3 is not designed, and can be any element on your page, as long as it is contained within number 2.

My trick for providing visual feedback on the dragdrop operation is by using a ControlTemplate that includes a Popup (to display the dragging content) and a ContentPresenter (that shows the draggable object). By mutating the position of the popup along with the mouse cursor you can get a nice drag/drop experience.

For example: the following XAML fragment allows me to drop an textblock on a listbox:

image

This effectively enables drag and drop from one of the buttons into the ListBox.

After you have given the DragDropManager an x:Name, you can hook into the 'drop' event and handle your logic there:

 

image

With the DragDropEventArgs, you get the DraggableItem that was dragged, the target control (which in this case can only be a ListBox) and the coordinates of the actual drop.

Drag Drop feedback is limited in this solution, but by applying new styles and templates you can do a lot. For example, the DraggableElement is fully skinnable using the Visual States that are defined in the default template. In the current version, this is the default template for a draggableElement:

image

As you can see there are states for MouseOver, Normal, Dragging and DropNotAllowed. Plenty to work with!

 

 

 

PS. I intend to release this code on codeplex, so I will have to find out how.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories:
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed