Treeview拖放没有目标节点

时间:2012-12-10 15:54:37

标签: c# winforms drag-and-drop treeview

我有两个TreeView,它们是分开的。

  • treeView1
  • treeView2

我实现了Drag and Drop功能,以便我可以从树上拖到另一个,并且它可以正常使用我找到here的代码,我必须处理3个事件。

问题是我的窗口设置如下:

enter image description here

正如您所看到的,Window2隐藏了我的Window1它的目的,需要保持这样。问题是我的Drag and DropWindow2Window1所以我无法指定目标节点。有没有办法简单地放入没有任何目的节点的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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

treeview_dragdrop的{​​{1}}更改为以下内容:

forms