1

我有两个TreeView单独的形式。

  • treeView1
  • treeView2

我实现了一个Drag and Drop功能,以便我可以从一个树拖到另一个,并且它与我在这里找到的代码一起工作,我必须处理 3 个事件。

事情是我的窗户的设置是这样的:

在此处输入图像描述

正如你所看到的,Window2隐藏我的Window1它是故意的,需要保持这样。问题是我Drag and Drop是从Window2Window1所以我不能指定一个目标节点。有没有办法简单地放入一个TreeView没有任何目标节点的节点并说在其他节点旁边创建一个父节点?


链接死的例子不:

private void Form1_Load(object sender, System.EventArgs e)
{
    this.treeView1.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
    this.treeView2.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
    this.treeView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
    this.treeView2.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
    this.treeView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);
    this.treeView2.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);   
}

private void treeView_ItemDrag(object sender,
        System.Windows.Forms.ItemDragEventArgs e)
{
    DoDragDrop(e.Item, DragDropEffects.Move);
}

private void treeView_DragEnter(object sender,
        System.Windows.Forms.DragEventArgs e)
{
    e.Effect = DragDropEffects.Move;
}

private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
    TreeNode NewNode;

    if(e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
    {
        Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
        TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);
            NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
        if(DestinationNode.TreeView != NewNode.TreeView)
        {     
            DestinationNode.Nodes.Add((TreeNode) NewNode.Clone());
            DestinationNode.Expand();
            //Remove Original Node
            NewNode.Remove();
        }
    }
}
4

1 回答 1

2

treeview_dragdrop将两者更改为forms以下内容:

   private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
    {
        TreeNode NewNode;

        if(e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
        {
            NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
            if (!(sender as TreeView).Nodes.Contains(NewNode))//Edit: add this if you don't want to add the same one again.
            {    
                 (sender as TreeView).Nodes.Add((TreeNode) NewNode.Clone());                 
                 NewNode.Remove(); //Edit: add this if you want to remove original one.
            } 
        }
    }
于 2012-12-10T16:52:29.290 回答