2013-08-20 50 views
-1

我想要未經檢查的子節點,如果父節點未檢查。根據我的代碼,如果我檢查了一個子節點父節點得到選定。這是寫入方式,但是當我未選中父節點時,子節點仍然保持檢查狀態。我在AfterCheck事件中完成了以下代碼。如果父節點未選中,如何取消選中子節點?

private bool updatingTreeView; 
     private void treSelector_AfterCheck(object sender, TreeViewEventArgs e) 
     { 
      if (updatingTreeView) return; 
      updatingTreeView = true; 
      SelectParents(e.Node, e.Node.Checked); 
      updatingTreeView = false; 
     } 

private void SelectParents(TreeNode node, Boolean isChecked) 
     { 
      var parent = node.Parent; 

      if (parent == null) 
      { 
       //CheckAllChildren(treSelector.Nodes, false); 
       return; 
      } 

      if (isChecked) 
      { 
       parent.Checked = true; // we should always check parent 
       SelectParents(parent, true); 
      } 
      else 
      { 
       if (parent.Nodes.Cast<TreeNode>().Any(n => n.Checked)) 
        return; // do not uncheck parent if there other checked nodes 

       SelectParents(parent, false); 
      } 
     } 

如何解決這個問題?

+0

你看過所有可用的事件,並調查每個人做的事情嗎?例如'TreeView AfterCheck事件'?如果你花時間滾動到頁面的右側,你會看到 – MethodMan

+0

這個代碼是向後做的,你想迭代子節點和注意父節點。請謹防TreeView中的[錯誤](http://stackoverflow.com/questions/3174412/winforms-treeview-recursively-check-child-nodes-problem/3174824#3174824),當您點擊太快時,使它變得不可靠。 –

回答

1

我認爲你可以這樣寫的另一種方法:前updatingtreeview=false

if (e.Node.Checked==false) 
      { 
       if (e.Node.Nodes.Count > 0) 
       { 
        /* Calls the CheckAllChildNodes method, passing in the current 
        Checked value of the TreeNode whose checked state changed. */ 
        this.CheckAllChildNodes(e.Node, e.Node.Checked); 
       } 
      } 

void checkChildNodes(TreeNode theNode, bool isChecked) 
{ 
    if (theNode == null) return; 
    theNode.Checked = isChecked; 
    foreach(TreeNode childNode in theNode.Nodes) 
    { 
     checkChildNodes(childNode, isChecked); 
    } 
} 
+0

第一次孩子節點沒有得到檢查時,我點擊第二次在兒童複選框它被檢查。 –

0

我加入以下的aftercheck事件代碼和方法是

private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked) 
     { 
      foreach (TreeNode node in treeNode.Nodes) 
      { 
       node.Checked = nodeChecked; 
       if (node.Nodes.Count > 0) 
       { 
        // If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
        this.CheckAllChildNodes(node, nodeChecked); 
       } 
      } 
     } 

是工作很好..

相關問題