UIElement.DesiredSize Propriedade

Definição

Obtém o tamanho que esse UIElement calculou durante a passagem de medida do processo de layout.

public:
 property Size DesiredSize { Size get(); };
Size DesiredSize();
public Size DesiredSize { get; }
var size = uIElement.desiredSize;
Public ReadOnly Property DesiredSize As Size

Valor da propriedade

O tamanho que esse UIElement calculou durante a passagem de medida do processo de layout.

Exemplos

Este exemplo consulta DesiredSize como parte da iteração filho para uma implementação ArrangeOverride .

// Second arrange all children and return final size of panel
protected override Size ArrangeOverride(Size finalSize)
{
    // Get the collection of children
    UIElementCollection mychildren = Children;

    // Get total number of children
    int count = mychildren.Count;

    // Arrange children
    // We're only allowing 9 children in this panel.  More children will get a 0x0 layout slot.
    int i;
    for (i = 0; i < 9; i++)
    {

        // Get (left, top) origin point for the element in the 3x3 block
        Point cellOrigin = GetOrigin(i, 3, new Size(100, 100));

        // Arrange child
        // Get desired height and width. This will not be larger than 100x100 as set in MeasureOverride.
        double dw = mychildren[i].DesiredSize.Width;
        double dh = mychildren[i].DesiredSize.Height;

        mychildren[i].Arrange(new Rect(cellOrigin.X, cellOrigin.Y, dw, dh));

    }

    // Give the remaining children a 0x0 layout slot
    for (i = 9; i < count; i++)
    {
        mychildren[i].Arrange(new Rect(0, 0, 0, 0));
    }


    // Return final size of the panel
    return new Size(300, 300);
}
'Second arrange all children and return final size of panel 
Protected Overrides Function ArrangeOverride(ByVal finalSize As Size) As Size
    'Get the collection of children 
    Dim mychildren As UIElementCollection = Children
    'Get total number of children 
    Dim count As Integer = mychildren.Count
    'Arrange children 
    'only allowing 9 children in this panel. More children will get a 0x0 layout slot. 
    Dim i As Integer
    For i = 0 To 8
        'Get (left, top) origin point for the element in the 3x3 block 
        Dim cellOrigin As Point = GetOrigin(i, 3, New Size(100, 100))
        'Arrange child 
        'Get desired height and width. This will not be larger than 100x100 as set in MeasureOverride. 
        Dim dw As Double = mychildren(i).DesiredSize.Width
        Dim dh As Double = mychildren(i).DesiredSize.Height
        mychildren(i).Arrange(New Rect(cellOrigin.X, cellOrigin.Y, dw, dh))
    Next
    For i = 9 To count - 1
        'Give the remaining children a 0x0 layout slot 
        mychildren(i).Arrange(New Rect(0, 0, 0, 0))
    Next
    'Return final size of the panel 
    Return New Size(300, 300)
End Function
'Calculate point origin of the Block you are in 
Protected Function GetOrigin(ByVal blockNum As Integer, ByVal blocksPerRow As Integer, ByVal itemSize As Size) As Point
    'Get row number (zero-based) 
    Dim row As Integer = CInt(Math.Floor(blockNum / blocksPerRow))
    'Get column number (zero-based) 
    Dim column As Integer = blockNum - blocksPerRow * row
    'Calculate origin 
    Dim origin As New Point(itemSize.Width * column, itemSize.Height * row)
    Return origin
End Function

Comentários

DesiredSize normalmente é verificado como um dos fatores de medida quando você implementa substituições de comportamento de layout, como ArrangeOverride ou MeasureOverride. Dependendo da lógica de layout do contêiner pai, DesiredSize pode ser totalmente respeitado, as restrições em DesiredSize podem ser aplicadas e essas restrições também podem alterar outras características do elemento pai ou do elemento filho. Por exemplo, um controle que dá suporte a regiões roláveis (mas opta por não derivar dos controles que já habilitam regiões roláveis) pode comparar o tamanho disponível com DesiredSize. Em seguida, o controle pode definir um estado interno que habilitou barras de rolagem na interface do usuário para esse controle. Ou DesiredSize pode ser ignorado e o elemento sempre obtém um layout dimensionado por outras considerações, como a verificação de valores de propriedade anexada.

DesiredSize não conterá um valor útil, a menos que pelo menos uma passagem de layout "Measure" tenha sido executada no elemento .

DesiredSize é realmente destinado apenas para uso quando você define seus próprios métodos de substituição de layout. Se você estiver apenas interessado no tamanho de um elemento na interface do usuário do aplicativo em tempo de execução, deverá usar as propriedades ActualWidth e ActualHeight . Você pode estar verificando o tamanho dessa maneira se um elemento for influenciado por técnicas de layout dinâmico, como star dimensionamento de células grid. Confie nos valores ActualWidth e ActualHeight somente em situações que certamente ocorrerão após a execução do layout: por exemplo, em Eventos carregados ou disparadas por ações do usuário que só são possíveis após a interface do usuário ter sido renderizada inicialmente.

Aplica-se a

Confira também