网上找的有一个BUG,就是父节点为空时会出错,已经修正,并实现了拖放时产生下划线,并且改变颜色,状态显示更加友好
把treeview改名为tvList,并把AllowDrop设置为True
添加一个全局变局,用于记录拖放的节点:
TreeNode lastNode = null;
然后添加以下代码:
private void tvList_DragDrop(object sender, DragEventArgs e)
{
TreeNode moveNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
if (moveNode.Parent == null)
{
if (lastNode != null)
{
lastNode.NodeFont = new Font("宋体", 10, FontStyle.Regular);
lastNode.ForeColor = tvList.ForeColor;
}
return;
}
//根据鼠标坐标确定要移动到的目标节点
Point pt;
TreeNode targeNode;
pt = ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y));
targeNode = this.tvList.GetNodeAt(pt);
if (moveNode.Parent == null && targeNode.Parent == null)
{
if (lastNode != null)
{
lastNode.NodeFont = new Font("宋体", 10, FontStyle.Regular);
lastNode.ForeColor = tvList.ForeColor;
}
return;
}
//如果目标节点无子节点则添加为同级节点,反之添加到下级节点的未端
TreeNode NewMoveNode = (TreeNode)moveNode.Clone();
if (targeNode.Nodes.Count == 0)
{
if(targeNode.Parent!=null)
targeNode.Parent.Nodes.Insert(targeNode.Index, NewMoveNode);
else
targeNode.Nodes.Insert(targeNode.Index, NewMoveNode);
}
else
{
targeNode.Nodes.Insert(targeNode.Nodes.Count, NewMoveNode);
}
//更新当前拖动的节点选择
tvList.SelectedNode = NewMoveNode;
//展开目标节点,便于显示拖放效果
targeNode.Expand();
//移除拖放的节点
moveNode.Remove();
if (lastNode != null)
{
lastNode.NodeFont = new Font("宋体", 10, FontStyle.Regular);
lastNode.ForeColor = tvList.ForeColor;
}
}
private void tvList_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void tvList_ItemDrag(object sender, ItemDragEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DoDragDrop(e.Item, DragDropEffects.Move);
}
}
private void tvList_DragOver(object sender, DragEventArgs e)
{
if (lastNode != null)
{
lastNode.NodeFont = new Font("宋体", 10, FontStyle.Regular);
lastNode.ForeColor = tvList.ForeColor;
}
Point pt= ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y));
TreeNode tmpNode = tvList.GetNodeAt(pt);
if (tmpNode != null)
{
lastNode = tmpNode;
tmpNode.NodeFont = new Font("宋体", 10, FontStyle.Underline | FontStyle.Italic);
tmpNode.ForeColor = Color.LightSalmon;
}
}