TreeNode 类

定义

表示 TreeView 的节点。Represents a node of a TreeView.

public ref class TreeNode : MarshalByRefObject, ICloneable, System::Runtime::Serialization::ISerializable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.TreeNodeConverter))]
[System.Serializable]
public class TreeNode : MarshalByRefObject, ICloneable, System.Runtime.Serialization.ISerializable
type TreeNode = class
    inherit MarshalByRefObject
    interface ICloneable
    interface ISerializable
Public Class TreeNode
Inherits MarshalByRefObject
Implements ICloneable, ISerializable
继承
派生
属性
实现

示例

下面的代码示例在TreeView控件中显示客户信息。The following code example displays customer information in a TreeView control. 根树节点显示客户名称,子树节点显示分配给每个客户的订单号。The root tree nodes display customer names, and the child tree nodes display the order numbers assigned to each customer. 在此示例中,1000客户显示每个订单15个订单。In this example, 1,000 customers are displayed with 15 orders each. TreeView TreeView Cursor TreeNode使用和方法EndUpdate可取消重画,并在创建和绘制对象时显示等待。 BeginUpdateThe repainting of the TreeView is suppressed by using the BeginUpdate and EndUpdate methods, and a wait Cursor is displayed while the TreeView creates and paints the TreeNode objects. 此示例要求您有一个Customer可以保存Order对象集合的对象。This example requires that you have a Customer object that can hold a collection of Order objects. 它还要求您已TreeView Form在上创建了控件的实例。It also requires that you have created an instance of a TreeView control on a Form.

// The basic Customer class.
ref class Customer: public System::Object
{
private:
   String^ custName;

protected:
   ArrayList^ custOrders;

public:
   Customer( String^ customername )
   {
      custName = "";
      custOrders = gcnew ArrayList;
      this->custName = customername;
   }


   property String^ CustomerName 
   {
      String^ get()
      {
         return this->custName;
      }

      void set( String^ value )
      {
         this->custName = value;
      }

   }

   property ArrayList^ CustomerOrders 
   {
      ArrayList^ get()
      {
         return this->custOrders;
      }

   }

};


// End Customer class
// The basic customer Order class.
ref class Order: public System::Object
{
private:
   String^ ordID;

public:
   Order( String^ orderid )
   {
      ordID = "";
      this->ordID = orderid;
   }


   property String^ OrderID 
   {
      String^ get()
      {
         return this->ordID;
      }

      void set( String^ value )
      {
         this->ordID = value;
      }

   }

};
// End Order class



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.
   myEnum = customerArray->GetEnumerator();
   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();
}

// The basic Customer class.
public class Customer : System.Object
{
   private string custName = "";
   protected ArrayList custOrders = new ArrayList();

   public Customer(string customername)
   {
      this.custName = customername;
   }

   public string CustomerName
   {      
      get{return this.custName;}
      set{this.custName = value;}
   }

   public ArrayList CustomerOrders 
   {
      get{return this.custOrders;}
   }

} // End Customer class 


// The basic customer Order class.
public class Order : System.Object
{
   private string ordID = "";

   public Order(string orderid)
   {
      this.ordID = orderid;
   }

   public string OrderID
   {      
      get{return this.ordID;}
      set{this.ordID = value;}
   }

} // End Order class

// 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();
}
Public Class Customer
   Inherits [Object]
   Private custName As String = ""
   Friend custOrders As New ArrayList()

   Public Sub New(ByVal customername As String)
      Me.custName = customername
   End Sub

   Public Property CustomerName() As String
      Get
         Return Me.custName
      End Get
      Set(ByVal Value As String)
         Me.custName = Value
      End Set
   End Property

   Public ReadOnly Property CustomerOrders() As ArrayList
      Get
         Return Me.custOrders
      End Get
   End Property
End Class


Public Class Order
   Inherits [Object]
   Private ordID As String

   Public Sub New(ByVal orderid As String)
      Me.ordID = orderid
   End Sub

   Public Property OrderID() As String
      Get
         Return Me.ordID
      End Get
      Set(ByVal Value As String)
         Me.ordID = Value
      End Set
   End Property
End Class

' 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

注解

集合包含分配给当前TreeNodeTreeNode所有子对象。 NodesThe Nodes collection holds all the child TreeNode objects assigned to the current TreeNode. 你可以添加、删除或克隆 a TreeNode; 当你执行此操作时,将添加、删除或克隆所有子树节点。You can add, remove, or clone a TreeNode; when you do this, all child tree nodes are added, removed, or cloned. TreeNode个都可以包含其他TreeNode对象的集合。Each TreeNode can contain a collection of other TreeNode objects. 这可能会导致很难确定循环访问集合时所在TreeView的位置。This can make it difficult to determine where you are in the TreeView when iterating through the collection. 若要确定树结构中的位置,请使用FullPath属性。To determine your location in a tree structure, use the FullPath property. 可以使用字符串值对字符串进行分析,以确定标签开始和结束的位置。TreeNode FullPath PathSeparatorThe FullPath string can be parsed using the PathSeparator string value to determine where a TreeNode label begins and ends.

通过显式Text设置属性设置标签。TreeNodeThe TreeNode label is set by setting the Text property explicitly. 替代方法是使用其中一个TreeNode具有Text表示属性的字符串参数的构造函数创建树节点。The alternative is to create the tree node using one of the TreeNode constructors that has a string parameter that represents the Text property. 如果显示TreeNode图像,则会在图像旁显示标签。The label is displayed next to the TreeNode image, if one is displayed.

若要在树节点旁边显示图像,请将ImageList分配ImageListImageTreeView控件的属性,并通过在ImageList属性中引用其索引值来分配。To display images next to the tree nodes, assign an ImageList to the ImageList property of the parent TreeView control and assign an Image by referencing its index value in the ImageList property. 如果处于未选中状态,则将Image 属性设置为要显示的的索引值。ImageIndex TreeNodeSet the ImageIndex property to the index value of the Image you want to display when the TreeNode is in an unselected state. 同样,将SelectedImageIndex属性设置为选择时TreeNode要显示的Image的索引值。Likewise, set the SelectedImageIndex property to the index value of the Image you want to display when the TreeNode is selected.

可以通过使用以下属性值来实现Nodes选择特定树节点和循环访问集合: FirstNodeLastNodeNextNodePrevNode NextVisibleNode、、 PrevVisibleNodeSelecting specific tree nodes and iterating through the Nodes collection can be achieved by using the following property values: FirstNode, LastNode, NextNode, PrevNode, NextVisibleNode, PrevVisibleNode. 将上述TreeNode某个属性返回的返回TreeView.SelectedNode到属性,以在TreeView控件中选择该树节点。Assign the TreeNode returned by one of aforementioned properties to the TreeView.SelectedNode property to select that tree node in the TreeView control.

可以展开树节点以显示子树节点的下一级。Tree nodes can be expanded to display the next level of child tree nodes. 用户可以TreeNode通过按下的TreeNode加号(+)按钮展开,如果显示了一个按钮, TreeNode或者可以通过调用Expand方法展开。The user can expand the TreeNode by pressing the plus (+) button next to the TreeNode, if one is displayed, or you can expand the TreeNode by calling the Expand method. 若要展开集合中的Nodes所有子树节点级别,请ExpandAll调用方法。To expand all child tree node levels in the Nodes collection, call the ExpandAll method. 您可以通过Collapse调用方法TreeNode折叠子级别,或者TreeNode,如果显示一个,用户可以按下的减号(-)按钮。You can collapse the child TreeNode level by calling the Collapse method, or the user can press the minus (-) button next to the TreeNode, if one is displayed. 还可以调用Toggle方法以在展开和折叠TreeNode状态之间交替。You can also call the Toggle method to alternate the TreeNode between the expanded and collapsed states.

树节点可以选择性地显示复选框。Tree nodes can optionally display a check box. 若要显示复选框,请将CheckBoxesTreeView属性设置为trueTo display the check boxes, set the CheckBoxes property of the TreeView to true. 对于处于选中状态的true树节点,属性设置为。CheckedThe Checked property is set to true for tree nodes that are in a checked state.

构造函数

TreeNode()

初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class.

TreeNode(SerializationInfo, StreamingContext)

使用指定的序列化信息和上下文初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class using the specified serialization information and context.

TreeNode(String)

用指定的标签文本初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class with the specified label text.

TreeNode(String, Int32, Int32)

用指定的标签文本以及树节点处于选定和未选定状态时所显示的图像来初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class with the specified label text and images to display when the tree node is in a selected and unselected state.

TreeNode(String, Int32, Int32, TreeNode[])

用指定的标签文本、子树节点以及树节点处于选定和未选定状态时所显示的图像来初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class with the specified label text, child tree nodes, and images to display when the tree node is in a selected and unselected state.

TreeNode(String, TreeNode[])

用指定的标签文本和子树节点初始化 TreeNode 类的新实例。Initializes a new instance of the TreeNode class with the specified label text and child tree nodes.

属性

BackColor

获取或设置树节点的背景色。Gets or sets the background color of the tree node.

Bounds

获取树节点的界限。Gets the bounds of the tree node.

Checked

获取或设置一个值,用以指示树节点是否处于选中状态。Gets or sets a value indicating whether the tree node is in a checked state.

ContextMenu

获取与此树节点关联的快捷菜单。Gets the shortcut menu that is associated with this tree node.

ContextMenuStrip

获取或设置与此树节点关联的快捷菜单。Gets or sets the shortcut menu associated with this tree node.

FirstNode

获取树节点集合中的第一个子树节点。Gets the first child tree node in the tree node collection.

ForeColor

获取或设置树节点的前景色。Gets or sets the foreground color of the tree node.

FullPath

设置从根树节点到当前树节点的路径。Gets the path from the root tree node to the current tree node.

Handle

获取树节点的句柄。Gets the handle of the tree node.

ImageIndex

获取或设置当树节点处于未选定状态时所显示图像的图像列表索引值。Gets or sets the image list index value of the image displayed when the tree node is in the unselected state.

ImageKey

获取或设置此树节点处于未选中状态时与其关联的图像的键。Gets or sets the key for the image associated with this tree node when the node is in an unselected state.

Index

获取树节点在树节点集合中的位置。Gets the position of the tree node in the tree node collection.

IsEditing

获取一个值,用以指示树节点是否处于可编辑状态。Gets a value indicating whether the tree node is in an editable state.

IsExpanded

获取一个值,用以指示树节点是否处于可展开状态。Gets a value indicating whether the tree node is in the expanded state.

IsSelected

获取一个值,用以指示树节点是否处于选定状态。Gets a value indicating whether the tree node is in the selected state.

IsVisible

获取一个值,用以指示树节点是否是完全可见或部分可见。Gets a value indicating whether the tree node is visible or partially visible.

LastNode

获取最后一个子树节点。Gets the last child tree node.

Level

获取 TreeView 控件中的树视图的深度(从零开始)。Gets the zero-based depth of the tree node in the TreeView control.

Name

获取或设置树节点的名称。Gets or sets the name of the tree node.

NextNode

获取下一个同级树节点。Gets the next sibling tree node.

NextVisibleNode

获取下一个可见树节点。Gets the next visible tree node.

NodeFont

获取或设置用于显示树节点标签文本的字体。Gets or sets the font that is used to display the text on the tree node label.

Nodes

获取分配给当前树节点的 TreeNode 对象的集合。Gets the collection of TreeNode objects assigned to the current tree node.

Parent

获取当前树节点的父树节点。Gets the parent tree node of the current tree node.

PrevNode

获取上一个同级树节点。Gets the previous sibling tree node.

PrevVisibleNode

获取上一个可见树节点。Gets the previous visible tree node.

SelectedImageIndex

获取或设置当树节点处于选定状态时所显示的图像的图像列表索引值。Gets or sets the image list index value of the image that is displayed when the tree node is in the selected state.

SelectedImageKey

获取或设置当树节点处于选中状态时显示在该节点中的图像的键。Gets or sets the key of the image displayed in the tree node when it is in a selected state.

StateImageIndex

获取或设置图像的索引,该图像用于在父 TreeNodeTreeView 属性设置为 false 时,指示 CheckBoxes 的状态。Gets or sets the index of the image that is used to indicate the state of the TreeNode when the parent TreeView has its CheckBoxes property set to false.

StateImageKey

获取或设置图像的键,该图像用于在父 TreeNodeTreeView 属性设置为 false 时,指示 CheckBoxes 的状态。Gets or sets the key of the image that is used to indicate the state of the TreeNode when the parent TreeView has its CheckBoxes property set to false.

Tag

获取或设置包含树节点有关数据的对象。Gets or sets the object that contains data about the tree node.

Text

获取或设置在树节点标签中显示的文本。Gets or sets the text displayed in the label of the tree node.

ToolTipText

获取或设置当鼠标指针悬停于 TreeNode 之上时显示的文本。Gets or sets the text that appears when the mouse pointer hovers over a TreeNode.

TreeView

获取树节点分配到的父树视图。Gets the parent tree view that the tree node is assigned to.

方法

BeginEdit()

开始编辑树节点标签。Initiates the editing of the tree node label.

Clone()

复制树节点和以此树节点为根的整个子树。Copies the tree node and the entire subtree rooted at this tree node.

Collapse()

折叠树节点。Collapses the tree node.

Collapse(Boolean)

折叠 TreeNode,并可选择折叠其子节点。Collapses the TreeNode and optionally collapses its children.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Deserialize(SerializationInfo, StreamingContext)

从指定的 TreeNode 加载 SerializationInfo 的状态。Loads the state of the TreeNode from the specified SerializationInfo.

EndEdit(Boolean)

终止编辑树节点标签。Ends the editing of the tree node label.

EnsureVisible()

确保树节点可见,并在必要时展开树节点和滚动树视图控件。Ensures that the tree node is visible, expanding tree nodes and scrolling the tree view control as necessary.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Expand()

展开树节点。Expands the tree node.

ExpandAll()

展开所有子树节点。Expands all the child tree nodes.

FromHandle(TreeView, IntPtr)

返回带有指定句柄并分配给指定树视图控件的树节点。Returns the tree node with the specified handle and assigned to the specified tree view control.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetNodeCount(Boolean)

返回子树节点的数目。Returns the number of child tree nodes.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
Remove()

从树视图控件中移除当前树节点。Removes the current tree node from the tree view control.

Serialize(SerializationInfo, StreamingContext)

TreeNode 的状态保存到指定的 SerializationInfoSaves the state of the TreeNode to the specified SerializationInfo.

Toggle()

将树节点切换为展开或折叠状态。Toggles the tree node to either the expanded or collapsed state.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

显式界面实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化 TreeNode 时所需的数据填充序列化信息对象。Populates a serialization information object with the data needed to serialize the TreeNode.

适用于

另请参阅