-1

我正在编写一个自定义面板,我想知道如何告诉我的孩子,当他们需要重新测量时,他们的父母也应该进行重新测量。

例如,其中一个孩子改变了它的宽度,父母也应该再次重新测量,导致他的父母也做重新测量,然后他的父母和他父母的父母等等..就像上升VisualTree. 我怎么做?

这是面板的测量代码..但是如何告诉父母也重新测量

protected override Size MeasureOverride(Size availableSize)
{
 double x;
 double y;
 var children = this.InternalChildren;
 for (int i = 0; i < children.Count; i++)
     {
       UIElement child = children[i];
       child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity);
       y += child.DesiredSize.Height;
       x = Math.Max(x, child.DesiredSize.Width);
      }
 return new Size(x, y);
}
4

1 回答 1

1

看看这个在左上角排列子元素的非常简单的自定义面板:

public class MyPanel : Panel
{
    protected override Size MeasureOverride(Size availableSize)
    {
        Trace.TraceInformation("MeasureOverride");

        var size = new Size();

        foreach (UIElement element in InternalChildren)
        {
            element.Measure(availableSize);

            size.Width = Math.Max(size.Width, element.DesiredSize.Width);
            size.Height = Math.Max(size.Height, element.DesiredSize.Height);
        }

        return size;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        Trace.TraceInformation("ArrangeOverride");

        foreach (UIElement element in InternalChildren)
        {
            element.Arrange(new Rect(element.DesiredSize));
        }

        return finalSize;
    }
}

如果您将它与 Button 子项一起使用,如下所示

<local:MyPanel>
    <local:MyPanel>
        <Button Width="100" Height="100" Click="Button_Click"/>
    </local:MyPanel>
</local:MyPanel>

和一个调整按钮大小的 Button_Click 处理程序

private void Button_Click(object sender, RoutedEventArgs e)
{
    ((FrameworkElement)sender).Width += 20;
}

您会观察到,在每个按钮上单击都会测量和排列父面板和祖父面板。跟踪输出如下所示:

CustomPanelTest.vshost.exe Information: 0 : MeasureOverride
CustomPanelTest.vshost.exe Information: 0 : MeasureOverride
CustomPanelTest.vshost.exe Information: 0 : ArrangeOverride
CustomPanelTest.vshost.exe Information: 0 : ArrangeOverride

因此无需在父面板上调用Measure或手动操作。Arrange

于 2013-02-09T21:49:49.067 回答