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:

<i:Interaction.Behaviors>
    <dd:DragDropBehavior IsDragSource="True"/>
</i:Interaction.Behaviors>

And the following 3 lines to a target element:

<i:Interaction.Behaviors>
    <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>
</i:Interaction.Behaviors>

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}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Background="Transparent">
                <i:Interaction.Behaviors>
                    <dd:DragDropBehavior IsDragSource="True"/>
                </i:Interaction.Behaviors>
                        
                <Run Text="{Binding Title}" /><Run Text=": "/><Run Text="{Binding Value}" />
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
        
<ListBox ItemsSource="{Binding Items2}" Grid.Column="1" DisplayMemberPath="Title">
    <i:Interaction.Behaviors>
        <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>
    </i:Interaction.Behaviors>
</ListBox>

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.

Follow

Get every new post delivered to your Inbox.

Join 25 other followers