我有一个树视图并尝试将节点移动到父节点(拖放),
是否有任何方法允许目标节点在鼠标悬停时显示背景颜色(左按钮仍然保持拖动项目)?
[更新] 怎么跟随代码不起作用?
private TreeNode nodeOver=null;
private void treeView_DragOver(object sender, DragEventArgs e)
{
Point p = treeView.PointToClient(new Point(e.X, e.Y));
nodeOver = treeView.GetNodeAt(p.X, p.Y);
nodeOver.BackColor = Color.Aquamarine;
}
private void treeView_DragLeave(object sender, EventArgs e)
{
nodeOver.BackColor = Color.White;
}
答案 0 :(得分:5)
您可以尝试这样的事情:
private void treeView_DragOver(object sender, DragEventArgs e)
{
ClearBackground(treeView.Nodes);
Point p = treeView.PointToClient(new Point(e.X, e.Y));
TreeNode node = treeView.GetNodeAt(p.X, p.Y);
node.BackColor = Color.Aquamarine;
}
private void ClearBackground(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
node.BackColor = Color.White;
ClearBackground(node.Nodes);
}
}
修改强>
这是一个不应导致闪烁的改进版本:
private void treeView_DragOver(object sender, DragEventArgs e)
{
Point p = treeView.PointToClient(new Point(e.X, e.Y));
TreeNode node = treeView.GetNodeAt(p.X, p.Y);
if (node.PrevVisibleNode != null)
{
node.PrevVisibleNode.BackColor = Color.White;
}
if (node.NextVisibleNode != null)
{
node.NextVisibleNode.BackColor = Color.White;
}
node.BackColor = Color.Aquamarine;
}
答案 1 :(得分:5)
Veldmius,你上面的回答是不可靠的,有点冗长。如果没有可用的上一个或下一个节点,则NextVisibleNode和PreviousVisibleNode将抛出空异常。
我会这样做的方式如下...... 转到设计器中树视图的属性。 设置HideSelection = False
然后用这两行代码连接dragover事件。
private void treeview1_DragOver(object sender, DragEventArgs e)
{
TreeNode node = treeview1.GetNodeAt(treeview1.PointToClient(new Point(e.X, e.Y)));
treeview1.SelectedNode = node;
}