2

当我扩展面板并制作简单的 ArrangeOverride 时,内容从中间而不是左上角开始。据我所知,新点 0,0 应该使内容从左上角开始。谁能解释这种行为?

当我缩放主窗口时,内容(文本)的左上角保持在主窗口的中间

在此处输入图像描述

Public Class AvoidInfiniteSizePanel
    Inherits Panel

    Protected Overrides Function MeasureOverride(availableSize As Size) As Size
        If Me.Children.Count = 1 Then
            Dim Content = Me.Children(0)
            Content.Measure(New Size(Double.MaxValue, Double.MaxValue))

            Dim MyDesiredSize As Windows.Size = New Size(Math.Max(Content.DesiredSize.Width, MinimalWidth), Math.Max(Content.DesiredSize.Height, MinimalHeight))
            Return MyDesiredSize
        Else
            Return MyBase.MeasureOverride(availableSize) 'Default gedrag
        End If
    End Function

    Protected Overrides Function ArrangeOverride(finalSize As Size) As Size
        If Me.Children.Count = 1 Then
            Me.Children(0).Arrange(New Rect(New Point(0, 0), finalSize))
        Else
            Return MyBase.ArrangeOverride(finalSize) 'Default gedrag
        End If    

    End Function
End Class

和 XAML:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:infiniteSizeTester"
                Title="MainWindow" Height="125" Width="230">
    <Grid>
        <local:AvoidInfiniteSizePanel>
            <TextBlock VerticalAlignment="Top" HorizontalAlignment="Left" >Why is this in the center instead of at position 0,0</TextBlock >
        </local:AvoidInfiniteSizePanel>
    </Grid>
</Window>
4

1 回答 1

1

finalSize您错过了从 ArrangeOverride返回值。因此,Panel 将其大小报告为 (0, 0)。由于它在其父 Grid 中居中,因此 TextBlock 出现在中心位置。

Protected Overrides Function ArrangeOverride(finalSize As Size) As Size
    If Me.Children.Count = 1 Then
        Me.Children(0).Arrange(New Rect(New Point(0, 0), finalSize))
        Return finalSize 'here
    Else
        Return MyBase.ArrangeOverride(finalSize)
    End If    
End Function

无论如何,我建议简化您的代码并像这样编写面板:

Public Class CustomPanel
    Inherits Panel

    Protected Overrides Function MeasureOverride(availableSize As Size) As Size
        Dim desiredSize As New Size(MinimalWidth, MinimalHeight)
        For Each child As UIElement In InternalChildren
            child.Measure(New Size(Double.PositiveInfinity, Double.PositiveInfinity))
            desiredSize.Width = Math.Max(desiredSize.Width, child.DesiredSize.Width)
            desiredSize.Height = Math.Max(desiredSize.Height, child.DesiredSize.Height)
        Next child
        Return desiredSize
    End Function

    Protected Overrides Function ArrangeOverride(finalSize As Size) As Size
        For Each child As UIElement In InternalChildren
            child.Arrange(New Rect(finalSize))
        Next child
        Return finalSize
    End Function
End Class
于 2013-04-22T17:09:31.060 回答