我正在尝试在同一控件中实现 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/