In Treeview, how to prevent certain Node NOT available for a parent dropdown target?

SmilingMoon 981 Reputation points

I develops UWP app for desktop using TreeView



I'm using TreeView and allow user to drag and drop to reorganize the content.

There are 'Folder' nodes and 'Item' node.

I do NOT want user to put 'Folder' node under Item node. Item node must not have any child.

How can I prevent or cancel the drag&drop move if the target node is Item?

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Richard Zhang-MSFT 6,926 Reputation points


    Welcome to our Microsoft Q&A platform!

    In order to determine the type of the dragged item and the type of the target item, we need to listen to the TreeView.DragItemsCompleted and TreeView.DragItemsStarting events.

    1. DragItemsStarting

    private TreeViewNode _tempParent;
    private void TreeView_DragItemsStarting(Microsoft.UI.Xaml.Controls.TreeView sender, Microsoft.UI.Xaml.Controls.TreeViewDragItemsStartingEventArgs args)
        var item = args.Items.First() as TreeViewNode;
        if (item != null)
            _tempParent = item.Parent;

    The purpose of listening to this event is to determine the parent of the dragged item before dragging the item. If the verification fails, we need to add the item to the child again.

    2. DragItemsCompleted

    private void TreeView_DragItemsCompleted(Microsoft.UI.Xaml.Controls.TreeView sender, Microsoft.UI.Xaml.Controls.TreeViewDragItemsCompletedEventArgs args)
        var parent = args.NewParentItem as TreeViewNode;
        var item = args.Items.First();
        if (parent == null)
            // drag to root
        else if(parent.Content is StorageFile) // Your verification conditions
            var dragNode = args.Items.First() as TreeViewNode;

    After the drag is completed, we will verify that the parent meets the requirements. If it does not, we will remove the item just dragged from the parent and fill it into the original parent.


    0 comments No comments

0 additional answers

Sort by: Most helpful