当我扩展面板并制作一个简单的ArrangeOverride时,内容从中间而不是左上角开始

时间:2013-04-22 14:56:29

标签: wpf vb.net xaml custom-controls

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

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

enter image description here

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>

1 个答案:

答案 0 :(得分:1)

您错过了从ArrangeOverride返回finalSize值。因此,小组报告其大小为(0,0)。由于它在其父网格中居中,因此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

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

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