Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2008/.NET Framework 3.5

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
DrawTreeNodeEventArgs (Clase)

Actualización: noviembre 2007

Proporciona datos para el evento DrawNode.

Espacio de nombres:  System.Windows.Forms
Ensamblado:  System.Windows.Forms (en System.Windows.Forms.dll)
Visual Basic (Declaración)
Public Class DrawTreeNodeEventArgs _
    Inherits EventArgs
Visual Basic (Uso)
Dim instance As DrawTreeNodeEventArgs
C#
public class DrawTreeNodeEventArgs : EventArgs
Visual C++
public ref class DrawTreeNodeEventArgs : public EventArgs
J#
public class DrawTreeNodeEventArgs extends EventArgs
JScript
public class DrawTreeNodeEventArgs extends EventArgs

Utilice el evento DrawNode para personalizar el aspecto de los nodos en un control TreeView mediante el dibujo del propietario.

Un control TreeView provoca el evento DrawNode cuando su propiedad TreeView..::.DrawMode se establece en TreeViewDrawMode..::.OwnerDrawAll o TreeViewDrawMode..::.OwnerDrawText y se muestra un nodo o se actualiza. El DrawTreeNodeEventArgs pasado al controlador de eventos contiene información sobre el nodo que se va a dibujar y proporciona métodos que le ayudarán a dibujar el nodo.

Utilice la propiedad State o Node para recuperar información sobre el nodo que se va a dibujar. Utilice la propiedad Graphics para hacer el dibujo real dentro del área especificada por la propiedad Bounds. Para hacer que el sistema operativo dibuje un nodo que no necesite ser dibujado por el propietario, establezca la propiedad DrawDefault en true.

Cuando la propiedad TreeView..::.DrawMode se establece en TreeViewDrawMode..::.OwnerDrawText, el área indicada por la propiedad Bounds sólo incluye la parte de la etiqueta del nodo. Cuando la propiedad TreeView..::.DrawMode se establece en TreeViewDrawMode..::.OwnerDrawAll, el área de la propiedad Bounds incluye el nodo completo, incluyendo el área normalmente utilizada para los iconos, casillas de verificación, signos de más y menos y líneas que conectan los nodos.

En el ejemplo de código siguiente se muestra cómo personalizar un control TreeView mediante el dibujo del propietario. El control TreeView del ejemplo muestra etiquetas de nodo opcionales junto a las etiquetas de nodo estándar. Las etiquetas de nodo se especifican utilizando la propiedad TreeNode..::.Tag. El control TreeView también utiliza colores personalizados, incluido un color de resaltado personalizado.

Puede personalizar la mayoría de los colores de TreeView estableciendo las propiedades de los colores, pero el color de resaltado de una selección no está disponible como propiedad. Además, el rectángulo de resalte de la selección predeterminado sólo se extiende alrededor de una etiqueta de nodo. Debe utilizarse la técnica de dibujo del propietario para dibujar las etiquetas de nodo así como un rectángulo de resalte personalizado suficientemente grande para incluir una etiqueta de nodo.

En el ejemplo, un controlador para el evento TreeView..::.DrawNode dibuja manualmente las etiquetas del nodo y el resalte de selección personalizado. Los nodos no seleccionados no necesitan personalización. Para estos elementos, la propiedad DrawDefault se establece en true para que sean dibujados por el sistema operativo.

Además, un controlador para el evento Control..::.MouseDown proporciona la prueba de detección. De manera predeterminada, un nodo sólo puede ser seleccionado haciendo clic en la región que rodea su etiqueta. El controlador del evento Control..::.MouseDown selecciona un nodo al que se ha hecho clic en cualquier lugar dentro de esta región o dentro de la región que rodea una etiqueta de nodo, si existe.

Visual Basic
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 (e.Node.Tag IsNot 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 (node.Tag IsNot 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 
C#
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;

    }

}
J#
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 
System..::.Object
  System..::.EventArgs
    System.Windows.Forms..::.DrawTreeNodeEventArgs
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

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

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker