Click here to Skip to main content
15,868,016 members
Articles / Desktop Programming / WPF

Drag and Drop in WPF - Part II

Rate me:
Please Sign up or sign in to vote.
4.94/5 (41 votes)
11 Nov 2009BSD4 min read 257.2K   11.4K   70   72
An article showing how to add drag and drop to a WPF application using the GongSolutions.Wpf.DragDrop library.

Image 1

Introduction

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.

Background

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:

XML
<ListBox Grid.Column="1" 
         ItemsSource="{Binding Schools.CurrentItem.Pupils}" 
         DisplayMemberPath="FullName"
         dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"
         dd:DragDrop.DragHandler="{Binding}"/>

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:

C#
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:

gong-wpf-dragdrop-ii1.png

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 :)

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

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

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:

XML
<ListBox Grid.Column="1" 
         ItemsSource="{Binding Schools.CurrentItem.Pupils}" 
         DisplayMemberPath="FullName"
         dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"
         dd:DragDrop.DragHandler="{Binding}" 
         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:

C#
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.

License

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


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: Question on use with treeview Pin
Steven Kirk23-Dec-09 0:51
Steven Kirk23-Dec-09 0:51 
GeneralCannot Drag to a listbox with group style Pin
bspro3-Dec-09 5:17
bspro3-Dec-09 5:17 
GeneralRe: Cannot Drag to a listbox with group style Pin
Steven Kirk7-Dec-09 9:55
Steven Kirk7-Dec-09 9:55 
GeneralRe: Cannot Drag to a listbox with group style Pin
Steven Kirk10-Dec-09 1:49
Steven Kirk10-Dec-09 1:49 
GeneralRe: Cannot Drag to a listbox with group style Pin
bspro15-Dec-09 2:44
bspro15-Dec-09 2:44 
GeneralRe: Cannot Drag to a listbox with group style Pin
Steven Kirk15-Dec-09 9:11
Steven Kirk15-Dec-09 9:11 
GeneralRe: Cannot Drag to a listbox with group style Pin
Prasad Thammineni12-Feb-10 11:18
Prasad Thammineni12-Feb-10 11:18 
GeneralRe: Cannot Drag to a listbox with group style Pin
Steven Kirk17-Feb-10 2:08
Steven Kirk17-Feb-10 2:08 
GeneralRe: Cannot Drag to a listbox with group style Pin
Prasad Thammineni23-Feb-10 11:57
Prasad Thammineni23-Feb-10 11:57 
GeneralRe: Cannot Drag to a listbox with group style Pin
Steven Kirk24-Feb-10 0:11
Steven Kirk24-Feb-10 0:11 
GeneralDataGrid DoubleClick Pin
joeliste22-Nov-09 23:28
joeliste22-Nov-09 23:28 
GeneralRe: DataGrid DoubleClick Pin
Steven Kirk22-Nov-09 23:42
Steven Kirk22-Nov-09 23:42 
GeneralRe: DataGrid DoubleClick Pin
Steven Kirk22-Nov-09 23:49
Steven Kirk22-Nov-09 23:49 
GeneralRe: DataGrid DoubleClick Pin
joeliste22-Nov-09 23:51
joeliste22-Nov-09 23:51 
GeneralRe: DataGrid DoubleClick Pin
joeliste23-Nov-09 0:11
joeliste23-Nov-09 0:11 
GeneralRe: DataGrid DoubleClick Pin
Steven Kirk23-Nov-09 0:14
Steven Kirk23-Nov-09 0:14 
QuestionUserControl Pin
joeliste17-Nov-09 22:52
joeliste17-Nov-09 22:52 
AnswerRe: UserControl Pin
Steven Kirk17-Nov-09 23:22
Steven Kirk17-Nov-09 23:22 
GeneralRe: UserControl Pin
joeliste17-Nov-09 23:37
joeliste17-Nov-09 23:37 
GeneralRe: UserControl Pin
Steven Kirk17-Nov-09 23:45
Steven Kirk17-Nov-09 23:45 
QuestionRe: UserControl Pin
joeliste18-Nov-09 3:05
joeliste18-Nov-09 3:05 
AnswerRe: UserControl Pin
Steven Kirk18-Nov-09 3:20
Steven Kirk18-Nov-09 3:20 
GeneralRe: UserControl Pin
joeliste18-Nov-09 3:33
joeliste18-Nov-09 3:33 

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

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