TreeView 类

显示标记项的分层集合,每个标记项用一个 TreeNode 来表示。

**命名空间:**System.Windows.Forms
**程序集:**System.Windows.Forms(在 system.windows.forms.dll 中)

语法

声明
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
Public Class TreeView
    Inherits Control
用法
Dim instance As TreeView
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
public class TreeView : Control
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] 
public ref class TreeView : public Control
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
public class TreeView extends Control
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
public class TreeView extends Control

备注

Nodes 集合包含分配给 TreeView 控件的所有 TreeNode 对象。此集合中的树节点称作根树节点。随后添加到根树节点上的任何树节点称作子节点。由于每个 TreeNode 都可以包含其他 TreeNode 对象的集合,您可能会在循环访问集合时觉得很难确定自己在树结构中的位置。您可以使用 PathSeparator 字符串值来分析 TreeNode.FullPath 字符串,以确定 TreeNode 标签的起始和终止位置。

可以在树节点旁显示图像,方法是将一个 ImageList 分配给 ImageList 属性,然后通过引用 ImageImageList 中的索引值来分配该 Image。使用下面的属性分配图像:

  • ImageIndex 属性设置为当树节点未选定时所显示的 Image 的索引值。

  • SelectedImageIndex 属性设置为当树节点被选定时要显示的 Image 的索引值。

ImageIndexSelectedImageIndex 属性值所引用的图像是所有分配给 Nodes 集合的树节点显示的默认图像。每个树节点都可以通过设置 TreeNode.ImageIndexTreeNode.SelectedImageIndex 属性来取代默认的图像。

树节点可以展开,以显示下一级子树节点。用户可以在 TreeNode 旁显示加号 (+) 按钮时通过单击加号 (+) 按钮来展开 TreeNode,或者可以通过调用 TreeNode.Expand 方法来展开 TreeNode。若要展开 Nodes 集合中的所有子树节点级别,请调用 ExpandAll 方法。若要折叠子 TreeNode 级别,可以调用 TreeNode.Collapse 方法,也可以在 TreeNode 旁显示减号 (-) 按钮时按减号 (-) 按钮。还可以通过调用 TreeNode.Toggle 方法在展开和折叠状态之间切换。

树节点可以选择性地显示复选框。若要显示复选框,请将 TreeViewCheckBoxes 属性设置为 true。对于处于选中状态的树节点,Checked 属性设置为 true

提示

BeforeCheckAfterCheck 事件内设置 TreeNode.Checked 属性将导致该事件被多次引发并可能产生意外行为。例如,您可以在递归更新子节点时在事件处理程序中设置 Checked 属性,以便用户不必逐个展开并选中每个节点。如果未将 TreeViewEventArgsAction 属性设置为 TreeViewAction.Unknown,则若要防止该事件被多次引发,需为仅执行递归代码的事件处理程序添加逻辑。有关如何进行此操作的示例,请参见 AfterCheckBeforeCheck 事件的示例部分。

通过设置 TreeView 控件的一些显示和样式属性,可以更改此控件的外观。如果将 ShowPlusMinus 设置为 true,则会分别在每个可展开或折叠的 TreeNode 旁显示加号或减号按钮。如果将 ShowRootLines 属性设置为 trueTreeView 则会显示联接所有根树节点之间的连线。通过将 ShowLines 属性设置为 true,可以显示子树节点与其根节点之间的连线。如果将 HotTracking 属性设置为 true,那么当鼠标指针移过树节点标签时,树节点标签的外观将发生变化。如果启用热跟踪,树节点标签将具有超链接的外观。也可以完全自定义 TreeView 控件的外观。若要执行此操作,请将 DrawMode 属性设置为 TreeViewDrawMode.Normal 以外的值并处理 DrawNode 事件。

提示

在运行时设置 CheckBoxesScrollableImageIndexSelectedImageIndex 属性时,将重新创建 TreeView 句柄(请参见 Control.RecreateHandle)以更新控件的外观。这将折叠除选定的 TreeNode 之外的所有树节点。

示例

下面的代码示例阐释了如何使用 TreeView 控件。

' Populates a TreeView control with example nodes. 
Private Sub InitializeTreeView()
    treeView1.BeginUpdate()
    treeView1.Nodes.Add("Parent")
    treeView1.Nodes(0).Nodes.Add("Child 1")
    treeView1.Nodes(0).Nodes.Add("Child 2")
    treeView1.Nodes(0).Nodes(1).Nodes.Add("Grandchild")
    treeView1.Nodes(0).Nodes(1).Nodes(0).Nodes.Add("Great Grandchild")
    treeView1.EndUpdate()
End Sub
// Populates a TreeView control with example nodes. 
private void InitializeTreeView()
{
    treeView1.BeginUpdate();
    treeView1.Nodes.Add("Parent");
    treeView1.Nodes[0].Nodes.Add("Child 1");
    treeView1.Nodes[0].Nodes.Add("Child 2");
    treeView1.Nodes[0].Nodes[1].Nodes.Add("Grandchild");
    treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great Grandchild");
    treeView1.EndUpdate();
}

下面更为复杂的代码示例在 TreeView 控件中显示客户信息。根树节点显示客户名称,子树节点显示分配给每个客户的订单编号。在本示例中,显示 1,000 个客户,每个客户有 15 个订单。使用 BeginUpdate 方法和 EndUpdate 方法可取消重新绘制 TreeView,在 TreeView 创建和绘制 TreeNode 对象时,显示等待 Cursor。本示例要求有一个 Customer 对象,它可存放 Order 对象的集合。还要求在应用程序目录中有一个名为 MyWait.cur 的光标文件,并已在 Form 上创建了 TreeView 控件的一个实例。

' Create a new ArrayList to hold the Customer objects.
Private customerArray As New ArrayList()

Private Sub FillMyTreeView()
   ' Add customers to the ArrayList of Customer objects.
   Dim x As Integer
   For x = 0 To 999
      customerArray.Add(New Customer("Customer" + x.ToString()))
   Next x

   ' Add orders to each Customer object in the ArrayList.
   Dim customer1 As Customer
   For Each customer1 In customerArray
      Dim y As Integer
      For y = 0 To 14
         customer1.CustomerOrders.Add(New Order("Order" + y.ToString()))
      Next y
   Next customer1

   ' Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = New Cursor("MyWait.cur")

   ' Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate()

   ' Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear()

   ' Add a root TreeNode for each Customer object in the ArrayList.
   Dim customer2 As Customer
   For Each customer2 In customerArray
      treeView1.Nodes.Add(New TreeNode(customer2.CustomerName))

      ' Add a child TreeNode for each Order object in the current Customer object.
      Dim order1 As Order
      For Each order1 In customer2.CustomerOrders
         treeView1.Nodes(customerArray.IndexOf(customer2)).Nodes.Add( _
    New TreeNode(customer2.CustomerName + "." + order1.OrderID))
      Next order1
   Next customer2

   ' Reset the cursor to the default for all controls.
   Cursor.Current = System.Windows.Forms.Cursors.Default

   ' Begin repainting the TreeView.
   treeView1.EndUpdate()
End Sub 'FillMyTreeView
// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList(); 

private void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for(int x=0; x<1000; x++)
   {
      customerArray.Add(new Customer("Customer" + x.ToString()));
   }

   // Add orders to each Customer object in the ArrayList.
   foreach(Customer customer1 in customerArray)
   {
      for(int y=0; y<15; y++)
      {
         customer1.CustomerOrders.Add(new Order("Order" + y.ToString()));    
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = new Cursor("MyWait.cur");
        
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate();

   // Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear();

   // Add a root TreeNode for each Customer object in the ArrayList.
   foreach(Customer customer2 in customerArray)
   {
      treeView1.Nodes.Add(new TreeNode(customer2.CustomerName));
          
      // Add a child treenode for each Order object in the current Customer object.
      foreach(Order order1 in customer2.CustomerOrders)
      {
         treeView1.Nodes[customerArray.IndexOf(customer2)].Nodes.Add(
           new TreeNode(customer2.CustomerName + "." + order1.OrderID));
      }
   }

   // Reset the cursor to the default for all controls.
   Cursor.Current = Cursors.Default;

   // Begin repainting the TreeView.
   treeView1.EndUpdate();
}
void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for ( int x = 0; x < 1000; x++ )
   {
      customerArray->Add( gcnew Customer( "Customer " + x ) );
   }
   
   // Add orders to each Customer object in the ArrayList.
   IEnumerator^ myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer1 = safe_cast<Customer^>(myEnum->Current);
      for ( int y = 0; y < 15; y++ )
      {
         customer1->CustomerOrders->Add( gcnew Order( "Order " + y ) );
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   ::Cursor::Current = gcnew System::Windows::Forms::Cursor( "MyWait.cur" );
   
   // Suppress repainting the TreeView until all the objects have been created.
   treeView1->BeginUpdate();
   
   // Clear the TreeView each time the method is called.
   treeView1->Nodes->Clear();
   
   // Add a root TreeNode for each Customer object in the ArrayList.
   while ( myEnum->MoveNext() )
   {
      Customer^ customer2 = safe_cast<Customer^>(myEnum->Current);
      treeView1->Nodes->Add( gcnew TreeNode( customer2->CustomerName ) );
      
      // Add a child treenode for each Order object in the current Customer object.
      IEnumerator^ myEnum = customer2->CustomerOrders->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Order^ order1 = safe_cast<Order^>(myEnum->Current);
         treeView1->Nodes[ customerArray->IndexOf( customer2 ) ]->Nodes->Add( gcnew TreeNode( customer2->CustomerName + "." + order1->OrderID ) );
      }
   }
   
   // Reset the cursor to the default for all controls.
   ::Cursor::Current = Cursors::Default;
   
   // Begin repainting the TreeView.
   treeView1->EndUpdate();
}
// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList();

private void FillMyTreeView()
{
    // Add customers to the ArrayList of Customer objects.
    for (int x = 0; x < 1000; x++) {
        customerArray.Add(new Customer("Customer"
            + ((Int32)x).ToString()));
    }
    // Add orders to each Customer object in the ArrayList.
    for (int iCtr = 0; iCtr < customerArray.get_Count(); iCtr++) {
        Customer customer1 = (Customer)customerArray.get_Item(iCtr);
        for (int y = 0; y < 15; y++) {
            customer1.get_CustomerOrders().Add(new Order("Order"
                + ((Int32)y).ToString()));
        }
    }
    // Display a wait cursor while the TreeNodes are being created.
    get_Cursor().set_Current(new Cursor("MyWait.cur"));
    // Suppress repainting the TreeView until all the objects have
    // been created.
    treeView1.BeginUpdate();
    // Clear the TreeView each time the method is called.
    treeView1.get_Nodes().Clear();
    // Add a root TreeNode for each Customer object in the ArrayList.
    for (int iCtr1 = 0; iCtr1 < customerArray.get_Count(); iCtr1++) {
        Customer customer2 = (Customer)customerArray.get_Item(iCtr1);
        treeView1.get_Nodes().Add(new TreeNode(customer2.get_CustomerName()));
        // Add a child treenode for each Order object in the current
        // Customer object.
        for (int iCtr2 = 0; iCtr2 < customer2.get_CustomerOrders().
            get_Count(); iCtr2++) {
            Order order1 = (Order)customer2.get_CustomerOrders().
                get_Item(iCtr2);
            treeView1.get_Nodes().
                get_Item(customerArray.IndexOf(customer2)).get_Nodes().
                Add(new TreeNode(customer2.get_CustomerName() + "."
                + order1.get_OrderID()));
        }
    }
    // Reset the cursor to the default for all controls.
    get_Cursor().set_Current(Cursors.get_Default());
    // Begin repainting the TreeView.
    treeView1.EndUpdate();
} //FillMyTreeView

继承层次结构

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
        System.Windows.Forms.TreeView
           System.ComponentModel.Design.ObjectSelectorEditor.Selector

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

TreeView 成员
System.Windows.Forms 命名空间
TreeNode 类