/// <summary> /// 正在拖拽的节点 /// </summary> private TreeNode DragNode = null; /// <summary> /// 节点来源 /// </summary> private TreeView NodeSource = null; /// <summary> /// 树形节点移动方向 /// </summary> private MoveTreeView MoveTo = MoveTreeView.NoMove; /// <summary> /// 当鼠标拖拽某相进入控件区域内时 /// </summary> private void TreeView_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } /// <summary> /// 当鼠标拖拽某节点时(两个控件的该事件都指向这个方法) /// </summary> private void TreeView_ItemDrag(object sender, ItemDragEventArgs e) { if (e.Item is TreeNode && e.Button == System.Windows.Forms.MouseButtons.Left && e.Item != null && sender is TreeView) { TreeView trv = sender as TreeView; TreeNode node = e.Item as TreeNode; if (node.Parent != null && trv.Tag != null) { int value = Convert.ToInt32(trv.Tag); MoveTo = (MoveTreeView)value; DragNode = node; NodeSource = trv; trv.DoDragDrop(node, DragDropEffects.Move); } } } /// <summary> /// 拖拽完成时发生的事件(两个控件的该事件都指向这个方法) /// </summary> private void TreeView_DragDrop(object sender, DragEventArgs e) { if (sender != null && sender is TreeView) { TreeView trv = sender as TreeView; if (trv.Tag != null) { MoveTreeView move = (MoveTreeView)Convert.ToInt32(trv.Tag); if (move == MoveTo) { DragNode = null; NodeSource = null; } else { Point p = trv.PointToClient(new Point(e.X, e.Y)); TreeNode node = trv.GetNodeAt(p); string path = GetClientPath(DragNode, DragNode.Text); NodeSource.Nodes.Remove(DragNode); node.Nodes.Add(DragNode); } } } } /// <summary> /// 属性节点移动方向 /// </summary> public enum MoveTreeView { /// <summary> /// 未移动 /// </summary> NoMove = -1, /// <summary> /// 上传(客户端拖拽到服务器端) /// </summary> ClientToServer = 0, /// <summary> /// 下载(服务器端拖拽到客户端) /// </summary> ServerToClient = 1 }
首先要将 TreeView 控件的 AllowDrop 属性置为 True