2017-08-04 58 views
3

我有一个TreeView和签署了“TreeViewConnections_AfterExpand”和“”事件。每个人TreeNode都包含MenuScript事件。和下面的代码:的TreeView AfterExpand事件somtimes不起作用C#

 //event 
private void TreeViewConnections_AfterExpand(object sender, TreeViewEventArgs e) 
    { 
     var activeKey = e.Node.ImageKey.Replace("Inactive", "Active"); 
     e.Node.ImageKey = activeKey; 
     e.Node.SelectedImageKey = activeKey; 
    } 

//event 
private void TreeViewConnections_MouseClick(object sender, MouseEventArgs e) 
    { 
     var currentNode = this.treeViewConnections.GetNodeAt(e.Location); 
     if (currentNode == null) return; 
     var currentBounds = currentNode.Bounds; 
     Rectangle bounds = new Rectangle(currentBounds.Left - ExpandIcon.Width, currentBounds.Y, currentBounds.Width - 5, currentBounds.Height); 
     if (bounds.Contains(e.Location)) return; 
     this.treeViewConnections.SelectedNode = currentNode; 

     if (e.Button == MouseButtons.Right) 
     { 
      SetupConnectionMenus(currentNode); 
     } 
    } 

    private void SetupConnectionMenus(TreeNode node) 
    { 
     var isOpened = node.Nodes.Count > 0; 
     if (node.ContextMenu == null) 
     { 
      var menu = new ContextMenuStrip(); 
      menu.Items.AddEx("Open Connection", node.Name + "_Open", !isOpened, onClick: OpenConnection_Click, context: node); 
      menu.Items.AddEx("Close Connection", node.Name + "_Close", isOpened, onClick: CloseConnection_Click, context: node); 
      node.ContextMenuStrip = menu; 
     } 
    } 

    //event 
    private void OpenConnection_Click(object sender, EventArgs e) 
    { 
     var menuItem = sender as ToolStripMenuItem; 
     var currentNode = menuItem.Tag as TreeNode; 
     OpenConnection(currentNode); 
    } 

    //event 
    private void CloseConnection_Click(object sender, EventArgs e) 
    { 
     var menuItem = sender as ToolStripMenuItem; 
     var currentNode = menuItem.Tag as TreeNode; 
     currentNode.Nodes.Clear(); 
     currentNode.Collapse(); 
    } 

private void OpenConnection(TreeNode node) 
    { 
     treeViewConnections.BeginUpdate(); 
     //add child node to the node. 
     treeViewConnections.EndUpdate(); 
     node.Expand(); //????? 
    } 

TreeViewConnections_AfterExpand事件有时不工作。如图所示:

enter image description here

但是在这种情况下,有没有别的东西,我需要做什么?

+0

Node.Expand()是否每次你期望被调用? – Reniuz

+0

是的。每次调用它,我希望它扩展子节点,并在同一时间更改“TreeViewConnections_AfterExpand”事件的节点图标 –

+0

昌节点图标。 –

回答

1

此问题是Node.Collapse和Node.Nodes.Clear()调用导致问题的原因。正确如下:

private void CloseConnection_Click(object sender, EventArgs e) 
    { 
     var menuItem = sender as ToolStripMenuItem; 
     var currentNode = menuItem.Tag as TreeNode; 
     currentNode.Collapse(); // Here will verify whether the current node has child nodes. 
     currentNode.Nodes.Clear(); 
    }