Saturday, January 31, 2009

Drag-and-Drop in a WPF TreeView


Update: Get the latest version of my DragDropManger by clicking here.

When it came to adding drag-and-drop support to my application, the unfortunate dearth of an easy-to-use solution for WPF TreeViews became apparent. The closest thing available was drag-and-drop support for ListViews provided by our beloved WPF guru, Josh Smith. So, with Josh's blessing, I set out to adapt his ListViewDragDropManager into a TreeViewDragDropManager. It was a lengthy learning process, but I'm happy to say that the port is complete and a robust solution for TreeView DnD is now available. To demonstrate this functionality, the download contains a modified version of "Demo 2" from my Code Project article.

Although many of the private helpers and event handlers in my port differ significantly from the original, the public interface remains nearly identical. So you can read Josh's article, the "Using the code" section in particular, to get started. But do note the differences. First, my class takes two type parameters (instead of one), which you can best understand in the context of my Code Project article. Second, whereas Josh's ProcessDrop event is optional, my class requires you to subscribe in order to actually move a dropped item.

The drag-and-drop setup code in the demo look like this:
var m = new TreeViewDragDropManager<SampleTreeNode, SampleTreeNodeView>( sampleTreeView );
m.ProcessDrop += delegate( object sender, ProcessDropEventArgs<SampleTreeNode> e ) {
e.DroppedItem.ParentNode = null; //move the selected item
e.NewParent.SubNodes.Insert( e.NewIndex, e.DroppedItem );
};