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

SmilingMoon 976 Reputation points
2020-03-10T19:44:17.737+00:00

I develops UWP app for desktop using TreeView

xmlns:ui="using:Microsoft.UI.Xaml.Controls"

<ui: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,921 Reputation points
    2020-03-13T05:53:58.927+00:00

    Hello,​

    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;
            parent.Children.Remove(dragNode);
            _tempParent.Children.Add(dragNode);
        }
    }
    

    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.

    Thanks.

    No comments

0 additional answers

Sort by: Most helpful