Compartilhar via


Como: Criar um elemento do painel personalizado

Exemplo

Este exemplo mostra como substituir o comportamento de layout padrão do elemento Panel e criar elementos de layout personalizados que derivam de Panel.

O exemplo define uma simples Panel elemento chamado PlotPanel personalizado, que posiciona elementos filho de acordo com duas coordenadas x e y. Nesse exemplo, x e y são definidas como 50; portanto, todos os elementos filho são posicionados naquele local nos eixos x e y.

Para implementar comportamentos de Panel personalizados, o exemplo usa os métodos MeasureOverride e ArrangeOverride. Cada método retorna os dados Size que são necessários para posicionar e renderizar elementos filho.

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
    }
}

For the complete sample, see Criar um exemplo de painel Personalizar simples.

Consulte também

Tarefas

Criar um exemplo de painel de quebra automática de conteúdo Personalizar

Conceitos

Panels Overview

Referência

Panel