Assembly: System.Windows.Forms (in system.windows.forms.dll)
Public Event DrawNode As DrawTreeNodeEventHandler
Dim instance As TreeView Dim handler As DrawTreeNodeEventHandler AddHandler instance.DrawNode, handler
public event DrawTreeNodeEventHandler DrawNode
public: event DrawTreeNodeEventHandler^ DrawNode { void add (DrawTreeNodeEventHandler^ value); void remove (DrawTreeNodeEventHandler^ value); }
/** @event */ public void add_DrawNode (DrawTreeNodeEventHandler value) /** @event */ public void remove_DrawNode (DrawTreeNodeEventHandler value)
JScript supporta l'utilizzo di eventi ma non la dichiarazione di nuovi.
Utilizzare questo evento per personalizzare l'aspetto dei nodi di un controllo TreeView mediante la creazione da parte del proprietario.
L'evento viene generato solo quando la proprietà DrawMode è impostata sui valori OwnerDrawAll o OwnerDrawText di TreeViewDrawMode. Nella tabella riportata di seguito viene illustrato come personalizzare l'oggetto TreeNode quando la proprietà DrawMode è impostata su uno dei valori indicati.
| Valore della proprietà DrawMode | Personalizzazione dell'oggetto TreeNode |
|---|---|
| OwnerDrawText | È possibile personalizzare l'area dell'etichetta di TreeNode. Tutti gli altri elementi di TreeNode vengono disegnati automaticamente. |
| OwnerDrawAll | È possibile personalizzare l'aspetto dell'intero oggetto TreeNode. Le icone, le caselle di controllo, i segni più e meno e le linee di connessione dei nodi devono essere disegnati manualmente, se si desidera visualizzarli. |
L'area occupata dal valore di TreeNode.Text se venisse creata utilizzando il tipo di carattere specificato dalla proprietà Font del controllo TreeView corrisponde all'area in cui è possibile fare clic su un nodo per selezionarlo ed è denominata area di hit test. Se si prevede di disegnare all'esterno di quest'area, è necessario fornire un codice personalizzato che seleziona un nodo quando viene fatto clic sulla relativa area visibile.
L'area di hit test corrisponde alla proprietà DrawTreeNodeEventArgs.Bounds quando si utilizza OwnerDrawText. Quando si utilizza OwnerDrawAll, tuttavia, la proprietà DrawTreeNodeEventArgs.Bounds comprende l'intera larghezza di TreeView. In questo caso, è possibile accedere all'area di hit test ottenendo il valore di DrawTreeNodeEventArgs.Node e accedendo alla relativa proprietà TreeNode.Bounds. È quindi possibile disegnare l'area di hit test del nodo all'interno di questi limiti oppure fornire un codice di hit test personalizzato. L'impostazione della proprietà TreeNode.NodeFont non comporta la modifica delle dimensioni dell'area di hit test, che vengono calcolate in base al tipo di carattere specificato per l'intero oggetto TreeView.
Per ulteriori informazioni sulla gestione di eventi, vedere Utilizzo degli eventi.
Nell'esempio di codice riportato di seguito viene illustrato come personalizzare un controllo TreeView mediante il disegno personalizzato. Il controllo TreeView utilizzato nell'esempio consente di visualizzare i tag di nodo facoltativi insieme alle etichette di nodo standard. I tag di nodo vengono specificati tramite la proprietà TreeNode.Tag. Il controllo TreeView utilizza inoltre colori personalizzati, tra cui un colore di evidenziazione.
È possibile personalizzare la maggior parte dei colori di TreeView impostando le proprietà relative al colore. La selezione del colore di evidenziazione, tuttavia, non è disponibile come proprietà. Inoltre, il rettangolo di evidenziazione della selezione predefinito si estende solo attorno all'etichetta di un nodo. Per creare i tag di nodo e disegnare un rettangolo di evidenziazione personalizzato sufficientemente grande da includere un tag di nodo è quindi necessario utilizzare la tecnica di creazione da parte del proprietario.
Nell'esempio, un gestore per l'evento DrawNode crea manualmente i tag di nodo e il rettangolo di evidenziazione della selezione personalizzato. I nodi non selezionati non richiedono alcuna personalizzazione. Per questi nodi, la proprietà DrawTreeNodeEventArgs.DrawDefault viene impostata su true in modo che vengano creati automaticamente dal sistema operativo.
Inoltre, un gestore per l'evento MouseDown fornisce il codice di hit test. Per impostazione predefinita, un nodo può essere selezionato solo facendo clic sull'area attorno alla relativa etichetta. Il gestore eventi MouseDown consente di selezionare un nodo su cui è stato fatto clic in un qualsiasi punto all'interno di quest'area o dell'area attorno a un tag di nodo, se presente.
Imports System Imports System.Drawing Imports System.Windows.Forms Public Class TreeViewOwnerDraw Inherits Form Private WithEvents myTreeView As TreeView ' Create a Font object for the node tags. Private tagFont As New Font("Helvetica", 8, FontStyle.Bold) Public Sub New() ' Create and initialize the TreeView control. myTreeView = New TreeView() myTreeView.Dock = DockStyle.Fill myTreeView.BackColor = Color.Tan myTreeView.CheckBoxes = True ' Add nodes to the TreeView control. Dim node As TreeNode Dim x As Integer For x = 1 To 3 ' Add a root node to the TreeView control. node = myTreeView.Nodes.Add(String.Format("Task {0}", x)) Dim y As Integer For y = 1 To 3 ' Add a child node to the root node. node.Nodes.Add(String.Format("Subtask {0}", y)) Next y Next x myTreeView.ExpandAll() ' Add tags containing alert messages to a few nodes ' and set the node background color to highlight them. myTreeView.Nodes(1).Nodes(0).Tag = "urgent!" myTreeView.Nodes(1).Nodes(0).BackColor = Color.Yellow myTreeView.SelectedNode = myTreeView.Nodes(1).Nodes(0) myTreeView.Nodes(2).Nodes(1).Tag = "urgent!" myTreeView.Nodes(2).Nodes(1).BackColor = Color.Yellow ' Configure the TreeView control for owner-draw. myTreeView.DrawMode = TreeViewDrawMode.OwnerDrawText ' Add a handler for the MouseDown event so that a node can be ' selected by clicking the tag text as well as the node text. AddHandler myTreeView.MouseDown, AddressOf myTreeView_MouseDown ' Initialize the form and add the TreeView control to it. Me.ClientSize = New Size(292, 273) Me.Controls.Add(myTreeView) End Sub 'New <STAThreadAttribute()> _ Shared Sub Main() Application.Run(New TreeViewOwnerDraw()) End Sub 'Main ' Draws a node. Private Sub myTreeView_DrawNode(ByVal sender As Object, _ ByVal e As DrawTreeNodeEventArgs) Handles myTreeView.DrawNode ' Draw the background and node text for a selected node. If (e.State And TreeNodeStates.Selected) <> 0 Then ' Draw the background of the selected node. The NodeBounds ' method makes the highlight rectangle large enough to ' include the text of a node tag, if one is present. e.Graphics.FillRectangle(Brushes.Green, NodeBounds(e.Node)) ' Retrieve the node font. If the node font has not been set, ' use the TreeView font. Dim nodeFont As Font = e.Node.NodeFont If nodeFont Is Nothing Then nodeFont = CType(sender, TreeView).Font End If ' Draw the node text. e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, _ e.Bounds.Left - 2, e.Bounds.Top) ' Use the default background and node text. Else e.DrawDefault = True End If ' If a node tag is present, draw its string representation ' to the right of the label text. If Not (e.Node.Tag Is Nothing) Then e.Graphics.DrawString(e.Node.Tag.ToString(), tagFont, _ Brushes.Yellow, e.Bounds.Right + 2, e.Bounds.Top) End If ' If the node has focus, draw the focus rectangle large, making ' it large enough to include the text of the node tag, if present. If (e.State And TreeNodeStates.Focused) <> 0 Then Dim focusPen As New Pen(Color.Black) Try focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot Dim focusBounds As Rectangle = NodeBounds(e.Node) focusBounds.Size = New Size(focusBounds.Width - 1, _ focusBounds.Height - 1) e.Graphics.DrawRectangle(focusPen, focusBounds) Finally focusPen.Dispose() End Try End If End Sub 'myTreeView_DrawNode ' Selects a node that is clicked on its label or tag text. Private Sub myTreeView_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Dim clickedNode As TreeNode = myTreeView.GetNodeAt(e.X, e.Y) If NodeBounds(clickedNode).Contains(e.X, e.Y) Then myTreeView.SelectedNode = clickedNode End If End Sub 'myTreeView_MouseDown ' Returns the bounds of the specified node, including the region ' occupied by the node label and any node tag displayed. Private Function NodeBounds(ByVal node As TreeNode) As Rectangle ' Set the return value to the normal node bounds. Dim bounds As Rectangle = node.Bounds If Not (node.Tag Is Nothing) Then ' Retrieve a Graphics object from the TreeView handle ' and use it to calculate the display width of the tag. Dim g As Graphics = myTreeView.CreateGraphics() Dim tagWidth As Integer = CInt(g.MeasureString( _ node.Tag.ToString(), tagFont).Width) + 6 ' Adjust the node bounds using the calculated value. bounds.Offset(tagWidth \ 2, 0) bounds = Rectangle.Inflate(bounds, tagWidth \ 2, 0) g.Dispose() End If Return bounds End Function 'NodeBounds End Class 'TreeViewOwnerDraw
using System; using System.Drawing; using System.Windows.Forms; public class TreeViewOwnerDraw : Form { private TreeView myTreeView; // Create a Font object for the node tags. Font tagFont = new Font("Helvetica", 8, FontStyle.Bold); public TreeViewOwnerDraw() { // Create and initialize the TreeView control. myTreeView = new TreeView(); myTreeView.Dock = DockStyle.Fill; myTreeView.BackColor = Color.Tan; myTreeView.CheckBoxes = true; // Add nodes to the TreeView control. TreeNode node; for (int x = 1; x < 4; ++x) { // Add a root node to the TreeView control. node = myTreeView.Nodes.Add(String.Format("Task {0}", x)); for (int y = 1; y < 4; ++y) { // Add a child node to the root node. node.Nodes.Add(String.Format("Subtask {0}", y)); } } myTreeView.ExpandAll(); // Add tags containing alert messages to a few nodes // and set the node background color to highlight them. myTreeView.Nodes[1].Nodes[0].Tag = "urgent!"; myTreeView.Nodes[1].Nodes[0].BackColor = Color.Yellow; myTreeView.SelectedNode = myTreeView.Nodes[1].Nodes[0]; myTreeView.Nodes[2].Nodes[1].Tag = "urgent!"; myTreeView.Nodes[2].Nodes[1].BackColor = Color.Yellow; // Configure the TreeView control for owner-draw and add // a handler for the DrawNode event. myTreeView.DrawMode = TreeViewDrawMode.OwnerDrawText; myTreeView.DrawNode += new DrawTreeNodeEventHandler(myTreeView_DrawNode); // Add a handler for the MouseDown event so that a node can be // selected by clicking the tag text as well as the node text. myTreeView.MouseDown += new MouseEventHandler(myTreeView_MouseDown); // Initialize the form and add the TreeView control to it. this.ClientSize = new Size(292, 273); this.Controls.Add(myTreeView); } // Clean up any resources being used. protected override void Dispose(bool disposing) { if (disposing) { tagFont.Dispose(); } base.Dispose(disposing); } [STAThreadAttribute()] static void Main() { Application.Run(new TreeViewOwnerDraw()); } // Draws a node. private void myTreeView_DrawNode( object sender, DrawTreeNodeEventArgs e) { // Draw the background and node text for a selected node. if ((e.State & TreeNodeStates.Selected) != 0) { // Draw the background of the selected node. The NodeBounds // method makes the highlight rectangle large enough to // include the text of a node tag, if one is present. e.Graphics.FillRectangle(Brushes.Green, NodeBounds(e.Node)); // Retrieve the node font. If the node font has not been set, // use the TreeView font. Font nodeFont = e.Node.NodeFont; if (nodeFont == null) nodeFont = ((TreeView)sender).Font; // Draw the node text. e.Graphics.DrawString(e.Node.Text, nodeFont, Brushes.White, Rectangle.Inflate(e.Bounds, 2, 0)); } // Use the default background and node text. else { e.DrawDefault = true; } // If a node tag is present, draw its string representation // to the right of the label text. if (e.Node.Tag != null) { e.Graphics.DrawString(e.Node.Tag.ToString(), tagFont, Brushes.Yellow, e.Bounds.Right + 2, e.Bounds.Top); } // If the node has focus, draw the focus rectangle large, making // it large enough to include the text of the node tag, if present. if ((e.State & TreeNodeStates.Focused) != 0) { using (Pen focusPen = new Pen(Color.Black)) { focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; Rectangle focusBounds = NodeBounds(e.Node); focusBounds.Size = new Size(focusBounds.Width - 1, focusBounds.Height - 1); e.Graphics.DrawRectangle(focusPen, focusBounds); } } } // Selects a node that is clicked on its label or tag text. private void myTreeView_MouseDown(object sender, MouseEventArgs e) { TreeNode clickedNode = myTreeView.GetNodeAt(e.X, e.Y); if (NodeBounds(clickedNode).Contains(e.X, e.Y)) { myTreeView.SelectedNode = clickedNode; } } // Returns the bounds of the specified node, including the region // occupied by the node label and any node tag displayed. private Rectangle NodeBounds(TreeNode node) { // Set the return value to the normal node bounds. Rectangle bounds = node.Bounds; if (node.Tag != null) { // Retrieve a Graphics object from the TreeView handle // and use it to calculate the display width of the tag. Graphics g = myTreeView.CreateGraphics(); int tagWidth = (int)g.MeasureString (node.Tag.ToString(), tagFont).Width + 6; // Adjust the node bounds using the calculated value. bounds.Offset(tagWidth/2, 0); bounds = Rectangle.Inflate(bounds, tagWidth/2, 0); g.Dispose(); } return bounds; } }
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;
public class TreeViewOwnerDraw extends Form
{
private TreeView myTreeView;
// Create a Font object for the node tags.
private Font tagFont = new Font("Helvetica", 8, FontStyle.Bold);
public TreeViewOwnerDraw()
{
// Create and initialize the TreeView control.
myTreeView = new TreeView();
myTreeView.set_Dock(DockStyle.Fill);
myTreeView.set_BackColor(Color.get_Tan());
myTreeView.set_CheckBoxes(true);
// Add nodes to the TreeView control.
TreeNode node;
for (int x = 1; x < 4; ++x) {
// Add a root node to the TreeView control.
node = myTreeView.get_Nodes().Add(String.Format("Task {0}",
(Int32)x));
for (int y = 1; y < 4; ++y) {
// Add a child node to the root node.
node.get_Nodes().Add(String.Format("Subtask {0}", (Int32)y));
}
}
myTreeView.ExpandAll();
// Add tags containing alert messages to a few nodes
// and set the node background color to highlight them.
myTreeView.get_Nodes().get_Item(1).get_Nodes().get_Item(0).
set_Tag("urgent!");
myTreeView.get_Nodes().get_Item(1).get_Nodes().get_Item(0).
set_BackColor(Color.get_Yellow());
myTreeView.set_SelectedNode(myTreeView.get_Nodes().get_Item(1).
get_Nodes().get_Item(0));
myTreeView.get_Nodes().get_Item(2).get_Nodes().get_Item(1).
set_Tag("urgent!");
myTreeView.get_Nodes().get_Item(2).get_Nodes().get_Item(1).
set_BackColor(Color.get_Yellow());
// Configure the TreeView control for owner-draw and add
// a handler for the DrawNode event.
myTreeView.set_DrawMode(TreeViewDrawMode.OwnerDrawText);
myTreeView.add_DrawNode(new DrawTreeNodeEventHandler(
myTreeView_DrawNode));
// Add a handler for the MouseDown event so that a node can be
// selected by clicking the tag text as well as the node text.
myTreeView.add_MouseDown(new MouseEventHandler(myTreeView_MouseDown));
// Initialize the form and add the TreeView control to it.
this.set_ClientSize(new Size(292, 273));
this.get_Controls().Add(myTreeView);
} //TreeViewOwnerDraw
// Clean up any resources being used.
protected void Dispose(boolean disposing)
{
if (disposing) {
tagFont.Dispose();
}
super.Dispose(disposing);
} //Dispose
/** @attribute STAThreadAttribute()
*/
public static void main(String[] args)
{
Application.Run(new TreeViewOwnerDraw());
} //main
// Draws a node.
private void myTreeView_DrawNode(Object sender, DrawTreeNodeEventArgs e)
{
// Draw the background and node text for a selected node.
if ((int)(e.get_State() & TreeNodeStates.Selected) != 0) {
// Draw the background of the selected node. The NodeBounds
// method makes the highlight rectangle large enough to
// include the text of a node tag, if one is present.
e.get_Graphics().FillRectangle(Brushes.get_Green(),
NodeBounds(e.get_Node()));
// Retrieve the node font. If the node font has not been set,
// use the TreeView font.
Font nodeFont = e.get_Node().get_NodeFont();
if (nodeFont == null) {
nodeFont = ((TreeView)sender).get_Font();
}
// Draw the node text.
e.get_Graphics().DrawString(e.get_Node().get_Text(),
nodeFont, Brushes.get_White(),
RectangleF.op_Implicit(Rectangle.Inflate(e.get_Bounds(), 2, 0)));
}
// Use the default background and node text.
else {
e.set_DrawDefault(true);
}
// If a node tag is present, draw its string representation
// to the right of the label text.
if (e.get_Node().get_Tag() != null) {
e.get_Graphics().DrawString(e.get_Node().get_Tag().ToString(),
tagFont, Brushes.get_Yellow(), e.get_Bounds().get_Right() + 2,
e.get_Bounds().get_Top());
}
// If the node has focus, draw the focus rectangle large, making
// it large enough to include the text of the node tag, if present.
if ((int)(e.get_State() & TreeNodeStates.Focused) != 0) {
Pen focusPen = new Pen(Color.get_Black());
try {
focusPen.set_DashStyle(System.Drawing.Drawing2D.DashStyle.Dot);
Rectangle focusBounds = NodeBounds(e.get_Node());
focusBounds.set_Size(new Size(focusBounds.get_Width() - 1,
focusBounds.get_Height() - 1));
e.get_Graphics().DrawRectangle(focusPen, focusBounds);
}
finally {
focusPen.Dispose();
}
}
} //myTreeView_DrawNode
// Selects a node that is clicked on its label or tag text.
private void myTreeView_MouseDown(Object sender, MouseEventArgs e)
{
TreeNode clickedNode = myTreeView.GetNodeAt(e.get_X(), e.get_Y());
if (NodeBounds(clickedNode).Contains(e.get_X(), e.get_Y())) {
myTreeView.set_SelectedNode(clickedNode);
}
} //myTreeView_MouseDown
// Returns the bounds of the specified node, including the region
// occupied by the node label and any node tag displayed.
private Rectangle NodeBounds(TreeNode node)
{
// Set the return value to the normal node bounds.
Rectangle bounds = node.get_Bounds();
if (node.get_Tag() != null) {
// Retrieve a Graphics object from the TreeView handle
// and use it to calculate the display width of the tag.
Graphics g = myTreeView.CreateGraphics();
int tagWidth = (int)(g.MeasureString(node.get_Tag().ToString(),
tagFont).get_Width()) + 6;
// Adjust the node bounds using the calculated value.
bounds.Offset(tagWidth / 2, 0);
bounds = Rectangle.Inflate(bounds, tagWidth / 2, 0);
g.Dispose();
}
return bounds;
} //NodeBounds
} //TreeViewOwnerDraw
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile per Pocket PC, Windows Mobile per Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.