UI Toolkit TreeView drag and drop

Hi,
I am trying to create a run time hierarchy using UI toolkit and TreeView but I can’t seem to find how to customize the drag and drop.
I want to parent the dragged label real GameObject to the dragged target real GameObject transform.
I am subscribing to
_treeView.handleDrop += OnHandleDrop;
And in OnHandleDrop i can get the target HierarchyItem like so:

private DragVisualMode OnHandleDrop(HandleDragAndDropArgs arg)
{
    
    if(arg.dropPosition == DragAndDropPosition.OverItem)
    {
        var targetTransform = (arg.target as HierarchyItem)?.Go.transform;
    }
    return DragVisualMode.Move;
}

How can I get the source HierarchyItem (the one that is being dragged)?

  public class HierarchyItem
  {
      public string Name { get; set; }
      public GameObject Go { get; set; }
      public int Depth { get; set; } // Determines the tree's indentation level
      public List<HierarchyItem> Children { get; set; } = new List<HierarchyItem>();
  }

I feel like I am missing something here, if anyone has any idea what I am doing wrong and how to get the source HierarchyItem I would love some help.

You can set it up during the setupDragAndDrop phase. You can add any data relevant to your drag operation by defining your own startDragArgs.SetGenericData. From what I can gather from the code you’re using, it would look something like:

treeview.setupDragAndDrop += args =>
{
    var startDragArgs = new StartDragArgs(args.startDragArgs.title, DragVisualMode.Move);
    startDragArgs.SetGenericData("Source_HierarchyItem", args.draggedElement as HierarchyItem);
    return startDragArgs;
}

Then in the handleDrop:

var item = args.dragAndDropData.GetGenericData("Source_HierarchyItem") as HierarchyItem;

For more info on drag and drop setup for ListView or TreeView, please refer to this manual page

Thanks!
That was it, changed it a tiny bit to this code:

_treeView.setupDragAndDrop += args =>
{
    var startDragArgs = new StartDragArgs(args.startDragArgs.title, DragVisualMode.Move);
    var firstId = args.selectedIds.First();
    var sourceItem = _treeView.GetItemDataForId<HierarchyItem>(firstId);
    startDragArgs.SetGenericData("Source_HierarchyItem", sourceItem);
    return startDragArgs;
};

Now it works perfectly :slight_smile:

1 Like