.NET Treeview NodeMouseClick 事件有延迟?

.NET Treeview NodeMouseClick Event has lag?

我有这个代码:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (treeView1.SelectedNode.Nodes.Count == 0)
            {
                MessageBox.Show("The node does not have any children.");
            }
        }

单击没有子节点的 treeView 节点时,事件触发似乎有延迟。

例如:

  1. 我单击带有子节点的父节点 - MessageBox 未触发
  2. 我单击没有子节点的子节点 - MessageBox 没有触发
  3. 我再次单击没有子节点的子节点 - 消息框触发
  4. 我单击带有子节点的父节点 - 消息框触发
  5. 我再次单击带有子节点的父节点 - 消息框未触发。

在调试期间,SelectedNode.Count 值似乎是之前点击的数字。

这是怎么回事?

您的问题源于 OnNodeMouseClick 在任何与选择相关的事件(OnBeforeSelectOnAfterSelect)之前被触发,这意味着 SelectedNode 您检查尚未更新。

如果您只关心选择的变化,请改为订阅BeforeSelect (with the ability to cancel the selection) or AfterSelect。这也将处理使用键盘更改的选择。

与选择相关的事件不同,即使所选节点不变NodeMouseClick仍会触发(例如,您正在点击一个已经选择的节点节点)。此外,顾名思义,这仅适用于鼠标单击不适用于使用键盘导航树。

要了解后台实际发生了什么,您可以查看 TreeView 的源代码,特别是事件的 WmNotify method. You'll see that NodeMouseClick is triggered by a windows NM_CLICK message. It then performs a Hit Test at the clicked (x,y) coordinate to look for a node under the mouse, and if found, give it back to you inside the TreeNodeMouseClickEventArgs 参数。

TLDR:订阅 NodeMouseClick 时,您的选择尚未更改(并且可能不会更改),但您可以通过检查事件参数来查看单击的节点。仅在使用鼠标而不是键盘时有效。