gpt4 book ai didi

C# WinForms - 在同一个 TreeViewControl 中拖放

转载 作者:可可西里 更新时间:2023-11-01 07:49:39 24 4
gpt4 key购买 nike

我正在尝试在同一控件中实现 TreeView 项目的拖放。

我希望能够将一个项目从一个节点移动到另一个节点。

这是我当前的代码,当我运行它时,我可以看到该项目已开始拖动,但 Windows 图标不允许将其拖放到控件上的任何节点。

我当前的代码

private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
DoDragDrop(e.Item, DragDropEffects.Move);
}

private void treeView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(TreeNode)))
{
TreeNode sourceNode = e.Data.GetData(typeof(TreeView)) as TreeNode;

var item = new TreeNode(sourceNode.Text);


System.Drawing.Point pt = ((TreeView)sender).PointToClient(new System.Drawing.Point(e.X, e.Y));
TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

DestinationNode.Nodes.Add(item);
DestinationNode.Expand();
}
}

最佳答案

只需将 treeView1_DragDrop 函数修改为:

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
// Retrieve the client coordinates of the drop location.
Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));

// Retrieve the node at the drop location.
TreeNode targetNode = treeView1.GetNodeAt(targetPoint);

// Retrieve the node that was dragged.
TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));

// Confirm that the node at the drop location is not
// the dragged node and that target node isn't null
// (for example if you drag outside the control)
if (!draggedNode.Equals(targetNode) && targetNode != null)
{
// Remove the node from its current
// location and add it to the node at the drop location.
draggedNode.Remove();
targetNode.Nodes.Add(draggedNode);

// Expand the node at the location
// to show the dropped node.
targetNode.Expand();
}
}

关于C# WinForms - 在同一个 TreeViewControl 中拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com