VladacusB
VladacusB

Reputation: 844

WPF TreeView drag items inside

What is the best strategy to implement drag and drop of items inside existing WPF TreeView control? It should be MVVM and it should have preview of item that is dragged from one position into another.

Had looked at some solutions. If I use Canvas, I can implement almost anything, but I would then need to start control from scratch which looks like reinventing the wheel considering that I need existing TreeView functionality. Had tried and PopUp and Thumb but I'm confused how to properly use them to implement this functionality. Also, it makes sense that I can use PreviewMouseOver for objects above destination TreeViewItems; I should be able to cancel drop action depending on the certain rules, for example I can not drop car object onto animals category.

Had checked some commercial solutions and they do have similar functionality already built in; but I was wondering if there is any free or open source solution too? Or at least to learn how they had achieved that functionality in commercial libraries?

Upvotes: 1

Views: 1205

Answers (1)

Keith Stein
Keith Stein

Reputation: 6724

I've implemented lots of drag and drop in WPF and I'll tell you up front that it takes some real work to do it well- but it can definitely be worth it.

If you want to implement it yourself, I'd suggest you study up on the msdn documentation here: Drag and Drop Overview. You'll need to implement the events listed in the section Drag-and-Drop Events.

To address specific points for your question:

  • "Rules" on what a specific drop target can accept as a drop are implemented in the DragOver event. During that event, you set e.Effects to None to indicate that a drop is not allowed, or to one of the other values to indicate how the drop is being interpreted.
  • A preview of the item being dragged would be best done using Adorners. You can create an adorner that follows the mouse during a drag operation and can even make it display an image of the UI element you're dragging using a VisualBrush.
    Just know that normal mouse events like MouseMove don't work while a drag and drop operation is in progress, so you'll have to stick with DragOver (which is only raised by elements with AllowDrop set to True), or use some p/invoke magic. You can check out my question on this exact topic along with the answer I eventually came up with: WPF - Track mouse during Drag & Drop while AllowDrop = False.

Upvotes: 2

Related Questions