Drag and Drop in Silverlight

Let’s do some drag & drop of Items between listboxes. The same thing could be used for rearranging items in a control(say listbox).
we can even show what item is getting dragged around
you can see a demo here 

(Note: updated code if you drag and drop between listboxes it should be fine. Error checking is not there, it will blowup if you click in the empty space in the listbox and mouseup and down on a item without dragging, need to fix those issues)

In the sample, I am using 3 listboxes each having different Itemtemplates

for the HitTest to work the listboxes have to be given some Background otherwise HitTest wont work

we are going to use the same events MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove events
the example here is using all listboxes, so the code is going to refer to listboxes

In XAML we drop a PopUp control with a ContentControl as child and set the opacity to .5, just to give it some effect

We start the DragDrop when the mouseleftbuttondown event is raised, we do a hittest and see if it is a listbox, If so start DragDrop

we are assuming that all the listboxes will have ItemTemplates defined

void StartDragDrop(ListBox sender,MouseEventArgs e)
{
DataTemplate dt = sender.ItemTemplate as DataTemplate;
dragSource = sender;
popupContent.Content = sender.SelectedItem;
popupContent.ContentTemplate = dt;
popup1.CaptureMouse();
captured = true;
mouseVerticalPosition = e.GetPosition(null).Y;
mouseHorizontalPosition = e.GetPosition(null).X;
popup1.HorizontalOffset = mouseHorizontalPosition;
popup1.VerticalOffset = mouseVerticalPosition;
}

We are getting the Datatemplate of the listbox and SelectedItem of the listbox we are interested in and setting the content of the ContentControl in the PopUp to the selectedItem of the ListBox.
Set the ContentTemplate property of the ContentControl to this DataTemplate.
Make sure we capture the mouse
For positioning the popup we set the HorizontalOffset and VerticalOffset properties of the Popup Control we added in the XAML

when the mouse moves we are going to adjust the same properties(HorizontalOffset and VerticalOffset) of the Popup Control to reflect mouse movement

when the MouseLeftButtonUp is raised we do a hitTest again to see the Destination(listBox)

void Page_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
List elements = (List)this.HitTest(e.GetPosition(null));
for(int i=0;i<elements.Count;i++){
ListBox lb = elements[i] as ListBox;
if (lb != null){
(lb.ItemsSource as ObservableCollection).Add(popupContent.Content as Customer);
(dragSource.ItemsSource as ObservableCollection).Remove(popupContent.Content as Customer);
break;
}
}
captured = false;
popupContent.Content = null;
popupContent.ContentTemplate = null;
popup1.ReleaseMouseCapture();
mouseVerticalPosition = -1;
mouseHorizontalPosition = -1;}  

 


Add and remove Items as necessary and we have to make sure we set the Content and ContentTemplate properties of the ContentControl in the Popup to null, release the mousecapture

download the updated source here

28 thoughts on “Drag and Drop in Silverlight

  1. Thanks, I noticed it after I posted the demo. As this demo doesn’t have any validations at all, it fails on the condition you mentioned as well as clicking (2 or 3 times) on the same listbox(it will remove the item and add it back again) will also throw an error.

  2. Thanks.

    I noticed it after I posted the demo. As this demo doesn’t have any validations at all, it fails on the condition you mentioned as well as clicking (2 or 3 times) on the same listbox(it will remove the item and add it back again) will also throw an error.

    Thanks for this post. Any plan to fix this error?

  3. Hi,

    Thanks to share this useful code 🙂

    When I do a MouseLeftDown click on a listbox item and start to move it the popup is still empty, I never see the popup, but when I drop it in the second listbox it works fine.

    Do you have an idea why I can’t see my popup ?
    (IsOpened property is True)

    I have another problem with this solution. When I remove the XAML page (doc.xaml) where I have these listboxes and the popup from the MainPage.xaml (ContentZone.Children.Clear) and I click on my menu to add on more time the XAML page (doc.xaml) in my MainPage.xaml I get an exception :

    A first chance exception of type ‘System.Windows.Markup.XamlParseException’ occurred in System.Windows.dll
    Additional information: The name already exists in the tree: popupContent. [Line: 0 Position: 0]

    Your project throws the same error if you try the same context of a MainPage where you load Page or Page2, when you load the Page.xaml for the second time you get the error of popupConent.

    Thanks in advance if you can help.

    desopedr

  4. Hi,

    I’ve resolved my problem :

    Set the popup IsOpened property to false by default, set it to true before CaptureMouse

    dragDropPopup.IsOpen = true; // desopedr
    dragDropPopup.CaptureMouse();

    and set it to false after ReleaseMouseCapture

    dragDropPopup.ReleaseMouseCapture();
    dragDropPopup.IsOpen = false; // desopedr

    I think the problem was that the popup with the IsOpened property set to true is considered in use and is never removed from my application.

  5. Hi, I am totally new to silverlight. Is it possible to run this application in .aspx page. I mean in asp.net web applications.

  6. Hi,

    Thanks for your valuable code that I have just downloaded but I am getting problem into it.

    While running I could see three listboxes but I cant drag-drop any of item from first listbox to second or third.

    I have also added breakpoint to ‘MouseButtonDown’ event but it seems that its not firing.

    Please let me know if I am doing anything wrong.

    Thanks & Regards

  7. Michael,
    As I dont have my own website, I used to uplod the app to microsoft’s silverlight streaming. this is one of the options there. I thought this is the option which will let users see the app in fewer clicks

  8. Thanks for this code.

    I have just upgraded that code for compatibility issue with Silverlight 2:

    replace:
    List elements = (List)this.HitTest(e.GetPosition(null));
    for (int i = 0; i < elements.Count; i++)
    {
    ListBox lb = elements[i] as ListBox;

    with:
    IEnumerable elements = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), this);

    foreach (UIElement elem in elements)
    {
    ListBox lb = elem as ListBox;

    The “canvas on top of listbox” is really tricky… Aaargh, I would like to have “WPF Preview” events in Silverlight… it is a big hole.

    Any other idea to workaround this?

  9. Very nice example! Would it also be possible to drop the ListBoxItem into a specific position in the TargetListbox – and moreover – indicate the drop position for the user during the drag (i.e. with a red line between the ListBoxItems in the TargetListbox?).
    Cheers,
    Andreas

  10. when i run the App on my local machine ,
    it is throwing error ,by saying that page does not conatin definition for HitTest

    1. Arif,
      HitTest was removed and we have to used this function
      VisualTreeHelper.FindElementsInHostCoordinates instead of HitTest

  11. Hi,
    I run this application and i have seen Three list box. Left top list box Filled by some city names. Then i draged in the Label and droped into to other (Right)List box. nothing happend.

Leave a reply to Arif shareef Cancel reply