TreeView.CollapseAll Метод

Определение

Свертывает все узлы дерева.

public:
 void CollapseAll();
public void CollapseAll ();
member this.CollapseAll : unit -> unit
Public Sub CollapseAll ()

Примеры

В следующем примере кода показано, как изменить состояние свертывания объекта TreeView таким образом, чтобы все проверенные узлы были видимыми. Сначала свернуты все узлы и для события добавляется BeforeExpand обработчик. Затем разворачиваются все узлы. Обработчик BeforeExpand событий определяет, есть ли у данного узла дочерние узлы, которые проверяются. Если узел не имеет проверенных дочерних элементов, расширение для этого узла отменяется. Чтобы разрешить стандартное расширение узла при щелчке знака "плюс" рядом с узлом, BeforeExpand обработчик событий удаляется.

Это поведение также можно реализовать путем обработки BeforeCollapse события, как показано в примере для этого раздела.

Полный пример см. в справочном CheckBoxes разделе.

private:
   void showCheckedNodesButton_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      // Disable redrawing of treeView1 to prevent flickering 
      // while changes are made.
      treeView1->BeginUpdate();
      
      // Collapse all nodes of treeView1.
      treeView1->CollapseAll();
      
      // Add the checkForCheckedChildren event handler to the BeforeExpand event.
      treeView1->BeforeExpand += checkForCheckedChildren;
      
      // Expand all nodes of treeView1. Nodes without checked children are 
      // prevented from expanding by the checkForCheckedChildren event handler.
      treeView1->ExpandAll();
      
      // Remove the checkForCheckedChildren event handler from the BeforeExpand 
      // event so manual node expansion will work correctly.
      treeView1->BeforeExpand -= checkForCheckedChildren;
      
      // Enable redrawing of treeView1.
      treeView1->EndUpdate();
   }

   // Prevent expansion of a node that does not have any checked child nodes.
   void CheckForCheckedChildrenHandler( Object^ /*sender*/, TreeViewCancelEventArgs^ e )
   {
      if (  !HasCheckedChildNodes( e->Node ) )
            e->Cancel = true;
   }


   // Returns a value indicating whether the specified 
   // TreeNode has checked child nodes.
   bool HasCheckedChildNodes( TreeNode^ node )
   {
      if ( node->Nodes->Count == 0 )
            return false;

      System::Collections::IEnumerator^ myEnum = node->Nodes->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         TreeNode^ childNode = safe_cast<TreeNode^>(myEnum->Current);
         if ( childNode->Checked )
                  return true;

         // Recursively check the children of the current child node.
         if ( HasCheckedChildNodes( childNode ) )
                  return true;
      }

      return false;
   }
private void showCheckedNodesButton_Click(object sender, EventArgs e)
{
    // Disable redrawing of treeView1 to prevent flickering 
    // while changes are made.
    treeView1.BeginUpdate();

    // Collapse all nodes of treeView1.
    treeView1.CollapseAll();

    // Add the checkForCheckedChildren event handler to the BeforeExpand event.
    treeView1.BeforeExpand += checkForCheckedChildren;

    // Expand all nodes of treeView1. Nodes without checked children are 
    // prevented from expanding by the checkForCheckedChildren event handler.
    treeView1.ExpandAll();

    // Remove the checkForCheckedChildren event handler from the BeforeExpand 
    // event so manual node expansion will work correctly.
    treeView1.BeforeExpand -= checkForCheckedChildren;

    // Enable redrawing of treeView1.
    treeView1.EndUpdate();
}

// Prevent expansion of a node that does not have any checked child nodes.
private void CheckForCheckedChildrenHandler(object sender, 
    TreeViewCancelEventArgs e)
{
    if (!HasCheckedChildNodes(e.Node)) e.Cancel = true;
}

// Returns a value indicating whether the specified 
// TreeNode has checked child nodes.
private bool HasCheckedChildNodes(TreeNode node)
{
    if (node.Nodes.Count == 0) return false;
    foreach (TreeNode childNode in node.Nodes)
    {
        if (childNode.Checked) return true;
        // Recursively check the children of the current child node.
        if (HasCheckedChildNodes(childNode)) return true;
    }
    return false;
}
Private Sub showCheckedNodesButton_Click(ByVal sender As Object, ByVal e As EventArgs)
    ' Disable redrawing of treeView1 to prevent flickering 
    ' while changes are made.
    treeView1.BeginUpdate()

    ' Collapse all nodes of treeView1.
    treeView1.CollapseAll()

    ' Add the CheckForCheckedChildren event handler to the BeforeExpand event.
    AddHandler treeView1.BeforeExpand, AddressOf CheckForCheckedChildren

    ' Expand all nodes of treeView1. Nodes without checked children are 
    ' prevented from expanding by the checkForCheckedChildren event handler.
    treeView1.ExpandAll()

    ' Remove the checkForCheckedChildren event handler from the BeforeExpand 
    ' event so manual node expansion will work correctly.
    RemoveHandler treeView1.BeforeExpand, AddressOf CheckForCheckedChildren

    ' Enable redrawing of treeView1.
    treeView1.EndUpdate()
End Sub

' Prevent expansion of a node that does not have any checked child nodes.
Private Sub CheckForCheckedChildren(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs)
    If Not HasCheckedChildNodes(e.Node) Then
        e.Cancel = True
    End If
End Sub

' Returns a value indicating whether the specified 
' TreeNode has checked child nodes.
Private Function HasCheckedChildNodes(ByVal node As TreeNode) As Boolean
    If node.Nodes.Count = 0 Then
        Return False
    End If
    Dim childNode As TreeNode
    For Each childNode In node.Nodes
        If childNode.Checked Then
            Return True
        End If
        ' Recursively check the children of the current child node.
        If HasCheckedChildNodes(childNode) Then
            Return True
        End If
    Next childNode
    Return False
End Function 'HasCheckedChildNodes

Комментарии

Метод CollapseAll сворачивает все TreeNode объекты, включая все дочерние узлы дерева, которые находятся в элементе TreeView управления .

Примечание

Состояние TreeNode объекта сохраняется. Например, предположим, что вы вызываете Expand метод для корневого узла дерева. Если дочерние узлы дерева ранее не были свернуты, они будут отображаться в ранее развернутом состоянии. CollapseAll Вызов метода гарантирует, что все узлы дерева будут отображаться в свернутом состоянии.

Применяется к

См. также раздел