Aggiornamento: novembre 2007
Visualizza un insieme gerarchico di elementi con etichetta, ciascuno dei quali rappresentato da un oggetto TreeNode.
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
<ComVisibleAttribute(True)> _ <DockingAttribute(DockingBehavior.Ask)> _ <ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _ Public Class TreeView _ Inherits Control
Dim instance As TreeView
[ComVisibleAttribute(true)] [DockingAttribute(DockingBehavior.Ask)] [ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] public class TreeView : Control
[ComVisibleAttribute(true)] [DockingAttribute(DockingBehavior::Ask)] [ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] public ref class TreeView : public Control
/** @attribute ComVisibleAttribute(true) */ /** @attribute DockingAttribute(DockingBehavior.Ask) */ /** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ public class TreeView extends Control
public class TreeView extends Control
L'insieme Nodes contiene tutti gli oggetti TreeNode assegnati al controllo TreeView. I nodi della struttura di questo insieme sono noti anche come nodi principali della struttura. Tutti i nodi della struttura aggiunti successivamente a un nodo principale della struttura vengono denominati nodi figli. Poiché ciascun oggetto TreeNode può contenere un insieme di altri oggetti TreeNode, può essere difficile determinare la posizione nella struttura in cui ci si trova quando si scorre un insieme. È possibile analizzare la stringa TreeNode.FullPath utilizzando il valore della stringa PathSeparator per determinare il punto di inizio e fine di un'etichetta di TreeNode.
Per visualizzare delle immagini accanto ai nodi della struttura, assegnare un oggetto ImageList alla proprietà ImageList e fare riferimento al valore di indice di Image in ImageList per assegnare tale oggetto Image. Per assegnare le immagini, utilizzare le seguenti proprietà:
-
Impostare la proprietà ImageIndex sul valore di indice dell'oggetto Image che si desidera visualizzare quando un nodo della struttura non è selezionato.
-
Impostare la proprietà SelectedImageIndex sul valore di indice dell'oggetto Image che si desidera visualizzare quando un nodo della struttura è selezionato.
Le immagini specificate dai valori delle proprietà ImageIndex e SelectedImageIndex sono le immagini predefinite visualizzate da tutti i nodi della struttura assegnati all'insieme Nodes. Per eseguire l'override delle immagini predefinite per singoli nodi della struttura è possibile impostare le proprietà TreeNode.ImageIndex e TreeNode.SelectedImageIndex.
È possibile espandere i nodi della struttura per visualizzare il livello successivo di nodi figlio della struttura. L'utente può espandere l'oggetto TreeNode selezionando il pulsante più (+), se visualizzato, accanto all'oggetto TreeNode oppure espandere l'oggetto TreeNode chiamando il metodo TreeNode.Expand. Per espandere tutti i livelli dei nodi figlio della struttura nell'insieme Nodes, chiamare il metodo ExpandAll. È possibile comprimere il livello figlio di TreeNode chiamando il metodo TreeNode.Collapse oppure selezionando il pulsante meno (-), se visualizzato, accanto all'oggetto TreeNode. Inoltre, è possibile chiamare il metodo TreeNode.Toggle per passare dallo stato esteso a quello compresso e viceversa.
Nei nodi della struttura è possibile visualizzare facoltativamente caselle di controllo. Per visualizzare le caselle di controllo, impostare la proprietà CheckBoxes dell'oggetto TreeView su true. La proprietà Checked è impostata su true per i nodi della struttura il cui stato è di selezione.
Nota:
|
|---|
|
Se la proprietà TreeNode.Checked viene impostata dall'evento BeforeCheck o AfterCheck, l'evento verrà generato più volte e potrebbe verificarsi un comportamento imprevisto. È possibile, ad esempio, impostare la proprietà Checked nel gestore eventi mentre si stanno aggiornando ricorsivamente i nodi figlio, in modo che l'utente non debba espanderli e selezionarli uno per uno. Per impedire che l'evento venga generato più volte, aggiungere al gestore eventi istruzioni in base alle quali il codice venga eseguito ricorsivamente solo se la proprietà Action dell'oggetto TreeViewEventArgs non è impostata su TreeViewAction.Unknown. Per una dimostrazione di questa tecnica, vedere la sezione relativa agli esempi degli eventi AfterCheck o BeforeCheck. |
È possibile modificare l'aspetto del controllo TreeView impostando alcune delle proprietà di visualizzazione e di stile. L'impostazione della proprietà ShowPlusMinus su true consente di visualizzare il pulsante più (+) o meno (-) accanto a ciascun oggetto TreeNode rispettivamente per espanderlo o comprimerlo. Impostando la proprietà ShowRootLines su true, nel controllo TreeView vengono visualizzate delle linee per collegare tutti i nodi principali della struttura. È possibile visualizzare linee che colleghino i nodi figlio della struttura ai rispettivi nodi principali impostando la proprietà ShowLines su true. Impostando la proprietà HotTracking su true, l'aspetto delle etichette del nodo principale cambia al passaggio del mouse su di esse. Quando intercettate, le etichette del nodo della struttura assumono l'aspetto di un collegamento ipertestuale. È inoltre possibile personalizzare completamente l'aspetto del controllo TreeView. A questo scopo, impostare la proprietà DrawMode su un valore diverso da TreeViewDrawMode.Normal e gestire l'evento DrawNode.
Nota:
|
|---|
|
Quando si impostano le proprietà CheckBoxes , Scrollable , ImageIndex e SelectedImageIndex in fase di esecuzione, l'handle di TreeView viene ricreato (vedere Control.RecreateHandle) in modo da aggiornare l'aspetto del controllo. Di conseguenza, tutti i nodi della struttura vengono compressi, ad eccezione dell'oggetto TreeNode selezionato. |
Nell'esempio di codice riportato di seguito viene illustrato l'utilizzo del controllo 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(); }
Nell'esempio di codice più complesso riportato di seguito vengono visualizzate informazioni relative ai clienti in un controllo TreeView. Nei nodi principali della struttura sono visualizzati i nomi dei clienti mentre nei nodi figlio della struttura sono visualizzati i numeri di ordine assegnati a ciascun cliente. In questo esempio, vengono visualizzati 1.000 clienti con 15 ordini ciascuno. Per evitare di ridisegnare il controllo TreeView, utilizzare i metodi BeginUpdate e EndUpdate; viene visualizzato un oggetto Cursor di attesa mentre nel controllo TreeView vengono creati e disegnati gli oggetti TreeNode. Per eseguire questo esempio è necessario che si disponga di un oggetto Customer che possa contenere un insieme di oggetti Order. Si richiede inoltre che nella directory dell'applicazione sia presente un file di cursore denominato MyWait.cur e che si sia creata un'istanza di un controllo TreeView su un oggetto Form.
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 'End Customer class Public Class Order Inherits [Object] Private ordID As String Public Sub New(ByVal orderid As String) Me.ordID = orderid End Sub 'New 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 ' End Order 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 'FillMyTreeView
// 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(); }
// 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 extends Object
{
private String custName = "";
protected ArrayList custOrders = new ArrayList();
public Customer(String customername)
{
this.custName = customername;
} //Customer
/** @property
*/
public String get_CustomerName()
{
return this.custName;
} //get_CustomerName
/** @property
*/
public void set_CustomerName(String value)
{
this.custName = value;
} //set_CustomerName
/** @property
*/
public ArrayList get_CustomerOrders()
{
return this.custOrders;
} //get_CustomerOrders
} //End Customer class
// The basic customer Order class.
public class Order extends Object
{
private String ordID = "";
public Order(String orderid)
{
this.ordID = orderid;
} //Order
/** @property
*/
public String get_OrderID()
{
return this.ordID;
} //get_OrderID
/** @property
*/
public void set_OrderID(String value)
{
this.ordID = value;
} //set_OrderID
} // 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"
+ ((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.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TreeView
System.ComponentModel.Design.ObjectSelectorEditor.Selector
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition , Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile per Smartphone, Windows Mobile per Pocket PC
.NET Framework e .NET Compact Framework non supportano tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Nota: