Click here to Skip to main content
Click here to Skip to main content

Drag and Drop in WPF - Part II

, 11 Nov 2009 BSD
Rate this:
Please Sign up or sign in to vote.
An article showing how to add drag and drop to a WPF application using the GongSolutions.Wpf.DragDrop library.


The is the second article on adding drag and drop to WPF applications using the GongSolutions.Wpf.DragDrop library. You can find the first part here: Drag and Drop in WPF Part I.


In the first article, I described how to add simple drag and drop behaviour to an ItemsControl using attached properties, and showed how drop behaviour could be customised by adding a drop handler. If you've not seen that article, I'd recommend reading it first.

Using the Code

In this article, I'll explain how to customise drag behaviour with drag handlers, how to display a drag adorner, and how to handle multiple selections.

Drag Handlers

In the same way that drop handlers allow us to write code to customise the handling of a drop on a control, drag handlers allow us to customise the drag itself. To demonstrate this, I'm going to use the example we constructed in part 1: the Schools example.

In our application, let's suppose that there are certain pupils who don't want to be moved out of their school. For the sake of this example, I'm going to hardcode a pupil by his name - "Tom Jefferson". In a real-life application, you'd obviously not be hard-coding information like this, but for the sake of keeping the example simple, that's exactly what I'm going to do!

To prevent Tom Jefferson being moved, we first need to add a DragHandler to the pupils ListBox:

<ListBox Grid.Column="1" 
         ItemsSource="{Binding Schools.CurrentItem.Pupils}" 
         dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"

Here, like the DropHandler, we're binding the drag handler to the MainViewModel. To make MainViewModel a drag handler, we need to implement the IDragSource interface:

void IDragSource.StartDrag(DragInfo dragInfo)
    PupilViewModel pupil = (PupilViewModel)dragInfo.SourceItem;

    if (pupil.FullName != "Tom Jefferson")
        dragInfo.Effects = DragDropEffects.Copy | DragDropEffects.Move;
        dragInfo.Data = pupil;

The IDragSource interface only defines a single method, StartDrag. In our implementation, we first check that the pupil is not named "Tom Jefferson", and if not, we tell the framework that both Copy and Move operations are allowed. Next, we set the drag data - both the Effects and Data properties must be set in a drag handler to allow a drag to start.

Run your program, and there it is: Tom Jefferson is no longer draggable.

Displaying a Drag Adorner

A drag adorner is a transparent image that shows a preview of the data being dragged. When we drag a pupil, we're going to display a drag adorner that looks like this:


Apologies for my lack of artistic skill on the icon, but you should get the idea. Feel free to use a better icon of your own Smile | :)

To show the adorner, first, we create a DataTemplate. We'll place it in the Window's Resources section:

    <DataTemplate x:Key="PupilDragAdorner">
            <Image Source="/Person.png" Width="64" 
            <TextBlock Text="{Binding FullName}" HorizontalAlignment="Center"/>

This DataTemplate consists of a StackPanel which vertically arranges two controls: an Image holding the icon and a TextBlock to display the pupil's name.

Now, we just need to set the DragAdornerTemplate attached property on the our ListBox:

<ListBox Grid.Column="1" 
         ItemsSource="{Binding Schools.CurrentItem.Pupils}" 
         dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"
         dd:DragDrop.DragAdornerTemplate="{StaticResource PupilDragAdorner}"/>

And Hey Presto! The adorner appears when you drag an item from the pupils ListBox.

Multiple Selections

If multiple selection is available on the source ItemsControl, then the default drag handler will handle this. However, when more than one item of data is dropped, you'll no longer receive a single object, but a collection of objects. The simplest way to deal with this in your drop handler is to check whether the dragged data is either an object of the accepted type or an IEnumerable of the accepted type. So, the DragOver method in the example method would need to change to this:

void IDropTarget.DragOver(DropInfo dropInfo)
    if ((dropInfo.Data is PupilViewModel || dropInfo.Data 
           is IEnumerable<PupilViewModel>) &&
        dropInfo.TargetItem is SchoolViewModel)
        dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight;
        dropInfo.Effects = DragDropEffects.Move;

Here we're checking to see if the data is a PupilViewModel or an IEnumerable<PupilViewModel>.

You'll also need to handle the possibility of a multiple selection in your IDropTarget.Drop method, but I'll leave that as an exercise to the reader.

Similarly, to enable an IDragSource to handle multiple selections, you need to look at the DragInfo.SourceItems property rather than the DragInfo.SourceItem property in your StartDrag method.

Points of Interest

Dragging a multiple selection is currently slightly broken. In WPF, if a user has made a multiple selection on an ItemsControl and then clicks on one of these items to start a drag, the multiple selection is cleared! So the framework checks to see if this is the case, and if so, swallows the click so that the multiple selection is not lost. However, this has the side-effect that if all items in the control are selected, there's nowhere for them to click to remove the multiple selection! Any hints on how to solve this problem will be gratefully received.


This article, along with any associated source code and files, is licensed under The BSD License


About the Author

Steven Kirk

United Kingdom United Kingdom
No Biography provided

Comments and Discussions

SuggestionWorkaround for e.Handled=true in DragSourcePreviewMouseLeftButtonDown Pinmemberurinspiration8-Dec-14 0:07 
QuestionHow use gong for UserControl PinmemberMember 93080535-Sep-13 21:37 
GeneralMy vote of 1 PinmemberDush Abe30-Jul-13 2:44 
GeneralRe: My vote of 1 Pinmemberurinspiration7-Dec-14 23:54 
QuestionDragging FROM a listbox with groupstyle PinmemberGlumph16-Jul-13 0:48 
QuestionHow do you enable the adorner to be visible when dragging out of the listview/box PinmemberMathias Benjamin Due Mortensen27-Jun-13 4:16 
QuestionSlider in ListboxItem does not work PinmemberJMHOOK22-Oct-12 0:55 
GeneralMy vote of 5 PinmemberJecho Jekov30-Sep-12 20:43 
QuestionWindows Explorer integration Pinmemberlill.LEIF1-Sep-12 13:35 
AnswerRe: Windows Explorer integration PinmemberSteven Kirk3-Sep-12 9:13 
GeneralRe: Windows Explorer integration Pinmemberlill.LEIF5-Sep-12 13:48 
QuestionStill dragging when a TextBox is selected PinmemberBragolgirith9-Aug-12 8:00 
AnswerRe: Still dragging when a TextBox is selected Pinmemberbalazs414-Jan-13 6:11 
QuestionDoesn't work Pinmembercaioshin16-Jul-12 11:53 
BugYou did not include the right source code PinmemberClifford Nelson9-May-12 12:03 
GeneralRe: You did not include the right source code Pinmembersbarne32-Jul-12 12:55 
GeneralRe: You did not include the right source code PinmemberVitor Barbosa6-Nov-12 9:12 
Suggestiondecouple ViewModel and View a bit more Pinmemberbitbonk12-Apr-12 22:17 
Questiondrag and drop between usercontrols Pinmembermichaelgr112-Mar-12 6:42 
Questiondifferent views Pinmembermichaelgr19-Mar-12 6:37 
QuestionMultiple drop templates PinmemberQaiser_Iftikhar27-Oct-11 23:59 
QuestionDragInfo null inside IDropTarget.Drop Pinmemberscomcleod18-Jul-11 6:15 
AnswerRe: DragInfo null inside IDropTarget.Drop Pinmemberscomcleod18-Jul-11 6:31 
GeneralRe: DragInfo null inside IDropTarget.Drop Pinmembersbarne32-Jul-12 12:58 
GeneralRe: DragInfo null inside IDropTarget.Drop Pinmemberscomcleod3-Jul-12 5:01 
QuestionDrop happening TWICE! Pinmembercbordeman23-Jun-11 11:00 
GeneralAbout DragInfo.DragStartPosition - e.GetPosition(null) is misleading when using with Context menu PinmemberVermaManish26-Apr-11 21:42 
GeneralInterface extended To CancelDrag() PinmemberDrNimnull1-Apr-11 10:22 
GeneralGet Source Parent PinmemberShady14u14-Mar-11 7:48 
GeneralMy vote of 5 Pinmemberkmorris14-Jan-11 6:52 
QuestionUsing with c# usercontrol hosted in winformHost Pinmembermach223-Jan-11 9:54 
GeneralMy vote of 5 Pinmemberko001u29-Dec-10 0:22 
GeneralAdded the ability to delay auto expand behavior so you hover over something to open it PinmemberDannyStaten16-Oct-10 12:02 
GeneralRe: Added the ability to delay auto expand behavior so you hover over something to open it PinmemberSteven Kirk18-Oct-10 4:02 
GeneralMy vote of 5 PinmemberDannyStaten14-Oct-10 7:40 
QuestionAuto Scrolling? PinmemberDannyStaten13-Oct-10 20:24 
AnswerRe: Auto Scrolling? PinmemberDannyStaten15-Oct-10 18:07 
GeneralQuestion for use on a treeview? - how to make child levels drag and droppable PinmemberDannyStaten12-Oct-10 19:57 
GeneralRe: Question for use on a treeview? - how to make child levels drag and droppable PinmemberSteven Kirk12-Oct-10 23:03 
GeneralRe: Question for use on a treeview? - how to make child levels drag and droppable [modified] PinmemberDannyStaten13-Oct-10 5:42 
GeneralRe: Question for use on a treeview? - how to make child levels drag and droppable PinmemberDannyStaten13-Oct-10 20:31 
GeneralBest solution for general MVVM works. Pinmemberzokbari9-Aug-10 19:05 
GeneralDrag n Drop from listbox to Custom Control PinmemberYer29-Jun-10 8:05 
QuestionRe: Drag n Drop from listbox to Custom Control PinmemberThomas_M15-Aug-11 3:58 
GeneralMultiSelect Issue PinmemberAnthony Osicka16-Jan-10 15:44 
GeneralRe: MultiSelect Issue PinmemberMember 78731031-Mar-12 1:12 
GeneralRe: MultiSelect Issue PinmemberVitor Barbosa13-Nov-12 8:10 
GeneralA messagebox at Listbox previewkeydown...dragging occurs from messgae location [modified] Pinmemberbspro11-Jan-10 4:33 
QuestionQuestion on use with treeview Pinmemberpiotri8522-Dec-09 11:28 
AnswerRe: Question on use with treeview PinmemberSteven Kirk23-Dec-09 1:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 11 Nov 2009
Article Copyright 2009 by Steven Kirk
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid