父母对儿童的规模

时间:2013-02-09 20:32:01

标签: wpf wpf-controls

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

例如,其中一个孩子改变了它的宽度,父母也应该重新测量,导致他的父母也做了重新测量,然后他的父母的父母和他父母的父母等等。它就像上升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);
}

1 个答案:

答案 0 :(得分: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处理程序,用于调整Button的大小

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

因此,无需在父级面板上手动调用MeasureArrange