Winform:TreeView节点折叠而不触发“节点单击”事件

本文关键字:节点 单击 节点单击 事件 TreeView 折叠 Winform | 更新日期: 2023-09-27 18:21:14

我需要防止节点崩溃时发生点击事件。我仍然希望节点折叠并隐藏其下的所有子节点,但如果可能的话,我不希望触发单击事件或选择节点。

Winform:TreeView节点折叠而不触发“节点单击”事件

如果你只需要影响你自己的代码,你可以使用这样的标志:

bool suppressClick = false;
private void treeView1_Click(object sender, EventArgs e)
{
    if (suppressClick) return;
    // else your regular code..
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    if (e.Node.IsExpanded)
         { suppressClick = false; }
    else { suppressClick = true; }
}

为了获得更多控制,您可能需要访问windows消息队列。。

我试图使用前一种解决方案,但它只起到了一种作用。我实现了一个字典,其中我保持节点展开/折叠的状态,所以当我发现状态相同时,这是一个实际的节点单击,而不是折叠/展开行为。

public class Yourclass {  
       var nodeStates = new Dictionary<int, bool>();
         public void addNode(Yourentity entity) 
         {
              TreeNode node= new TreeNode(entity.Name);
              node.Tag = entity;
              tree.Nodes.Add(entity);
              nodeStates.Add(entity.Id, true /* expanded in this case but doesn't matter */);
         }
       private void TreeControl_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
         var entity = (Yourentity )e.Node.Tag;
         bool state = nodeStates[entity.Id];
         // If was expanded or collapsed values will be different
         if (e.Node.Nodes.Count > 0 && (e.Node.IsExpanded != state))
         {
            // We update the state
             nodeStates[entity.Id] = e.Node.IsExpanded;
             return;
         }
         /* Put here your actual node click code */
     }
}