Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag-Drop in treeview, insert between nodes

I'm populating a TreeView through a XmlDataProvider, and have already implemented Drag-and-drop functionality, so I can move nodes around, and drop nodes from other locations.

But I have only implemented the simplest form; when you drop, it's inserted as a child to the node which on which it is dropped. This functionality works as intended. But I also want the ability to drop an item between two nodes, so that it becomes a sibling instead.

How should I proceed to solve this?

Currently I'm using a HierarchicalDataTemplate, with a StackPanel:

<HierarchicalDataTemplate x:Key="XmlTreeTemplate">
   <HierarchicalDataTemplate.ItemsSource>
     <Binding XPath="child::node()" />
   </HierarchicalDataTemplate.ItemsSource>
   <StackPanel
      AllowDrop="True"
      DragEnter="StackPanelDragEnter"
      DragLeave="StackPanelDragLeave"
      DragOver="StackPanelDragOver"
      ...

The Drop event is on the TreeView.

like image 639
AkselK Avatar asked Nov 28 '11 14:11

AkselK


1 Answers

During DragOver you can determine if your mouse position is above or below your TreeView Node with this method:

    public static bool IsInFirstHalf(FrameworkElement container, Point mousePosition, Orientation orientation)
    {
        if (orientation == Orientation.Vertical)
        {
            return mousePosition.Y < container.ActualHeight / 2;
        }
        return mousePosition.X < container.ActualWidth / 2;
    }

Then display an insertion adorner before/after your node. On Drop create a new node either before ( child of the parent node) or after ( sibling) the dropped on node.

like image 92
SvenG Avatar answered Oct 27 '22 15:10

SvenG