Cómo: Crear un elemento de panel personalizado

Actualización: noviembre 2007

Ejemplo

En este ejemplo se muestra cómo invalidar el comportamiento de diseño predeterminado del elemento Panel y crear elementos de diseño personalizados derivados de Panel.

En este ejemplo se define un elemento Panel personalizado simple llamado PlotPanel, que coloca elementos secundarios según dos coordenadas x e y codificadas de forma rígida. En este ejemplo, x y y se establecen en 50; por consiguiente, todos los elementos secundarios se colocan en esa ubicación en los ejes x e y.

Para implementar comportamientos de Panel personalizados, en el ejemplo se utilizan los métodos MeasureOverride y ArrangeOverride. Cada método devuelve los datos de Size necesarios para colocar y representar elementos secundarios.

Public Class PlotPanel
    Inherits Panel
    'Override the default Measure method of Panel.

    Protected Overrides Function MeasureOverride(ByVal availableSize As System.Windows.Size) As System.Windows.Size
        Dim childSize As Size = CType(availableSize, Size)
        For Each child As UIElement In InternalChildren
            child.Measure(childSize)
        Next
        Return MyBase.MeasureOverride(availableSize)
    End Function
    Protected Overrides Function ArrangeOverride(ByVal finalSize As System.Windows.Size) As System.Windows.Size
        For Each child As UIElement In InternalChildren
            Dim x As Double = 50
            Dim y As Double = 50
            child.Arrange(New Rect(New System.Windows.Point(x, y), child.DesiredSize))
        Next
        Return MyBase.ArrangeOverride(finalSize)
    End Function
End Class
public class PlotPanel : Panel
{
    // Default public constructor
    public PlotPanel()
        : base()
    {
    }

    // Override the default Measure method of Panel
    protected override Size MeasureOverride(Size availableSize)
    {
        Size panelDesiredSize = new Size();

        // In our example, we just have one child. 
        // Report that our panel requires just the size of its only child.
        foreach (UIElement child in InternalChildren)
        {
            child.Measure(availableSize);
            panelDesiredSize = child.DesiredSize;
        }

        return panelDesiredSize ;
    }
    protected override Size ArrangeOverride(Size finalSize)
    {
        foreach (UIElement child in InternalChildren)
        {
            double x = 50;
            double y = 50;

            child.Arrange(new Rect(new Point(x, y), child.DesiredSize));
        }
        return finalSize; // Returns the final Arranged size
    }
}

Para obtener el ejemplo completo, vea Ejemplo Create a Simple Custom Panel.

Vea también

Tareas

Ejemplo Create a Custom Content-Wrapping Panel

Conceptos

Información general sobre elementos Panel

Referencia

Panel