Tree drag and drop, insert between nodes

I populate the TreeView through XmlDataProvider and have already implemented the Drag-and-drop function, so I can move nodes and delete nodes from other places.

But I just applied the simplest form; when you drop it, it is inserted as a child of the node on which it is discarded. This functionality works as intended. But I also want the ability to drop an element between two nodes, so that instead it becomes a brother.

How do I solve this problem?

I am currently using 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 in the TreeView.

+4
source share
1 answer

During DragOver, you can determine if your mouse position is above or below your TreeView Node using 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 the adorner insert before / after node. In Drop, create a new Node either before (the child of the parent node) or after (sibling) dropped to the node.

+5
source

Source: https://habr.com/ru/post/1383438/


All Articles