WPF Drag and Drop implementation

Some time ago I searched how to implement the drag and drop functionality in my WPF application. But all examples that I found either contained much of unmaintenable code or worked only for a specific task and it was difficult to add that code into my existing application.

But recently in the Microsoft training course book (10262A Developing Windows Applications) I’ve found quite good example how to implement this functionality by using expression blend behaviors. By the way, the actual implementation were taken from this post.

Now it is very easy to use the drag and drop out of the box, just add the following 3 lines to a source element:

    <dd:DragDropBehavior IsDragSource="True"/>

And the following 3 lines to a target element:

    <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>

The i prefix is defined as xmlns:i=”clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity”, you can use this library after you install Expression Blend SDK or you can find it in the archive attached to this post.

Which element is the source and which one is the target – you should determine it logically. For example, if you want to move items from one ListBox to another one, the drag source will be the item template of the first ListBox (because it is the item which is dragged), the drop target will be the second ListBox itself (although it is still possible to set the drop target to the item template, it doesn’t work well for the empty listbox).
The code will look something like this:

<ListBox ItemsSource="{Binding Items1}">
            <TextBlock Background="Transparent">
                    <dd:DragDropBehavior IsDragSource="True"/>
                <Run Text="{Binding Title}" /><Run Text=": "/><Run Text="{Binding Value}" />
<ListBox ItemsSource="{Binding Items2}" Grid.Column="1" DisplayMemberPath="Title">
        <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>

And here is how it looks after you run the application:
wpf drag and drop sample

The source code of the behavior and sample application you can download here: WpfDragDrop.zip
If you want some extra features – you can freely write your suggestions in comments, I’ll think what I can do.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: