重写MeasureOverride和ArrangeOverride时,不会绘制WPF UserControl

时间:2010-03-09 13:47:59

标签: wpf user-controls measureoverride

我的UserControl看起来像这样:

<UserControl
    MaxHeight="32"
    MaxWidth="32"
    MinHeight="25"
    MinWidth="25">
    <DockPanel>
        <!-- some stuff -->
    </DockPanel>
</UserControl>

除了最小/最大尺寸约束之外,我希望控件始终用Width = Height绘制。所以我覆盖了MeasureOverrideArrangeOverride

protected override Size MeasureOverride(Size availableSize)
{
    var resultSize = new Size(0, 0);
    ((UIElement)Content).Measure(availableSize);
    var sideLength = Math.Min(((UIElement)Content).DesiredSize.Width, ((UIElement)Content).DesiredSize.Height);

    resultSize.Width = sideLength;
    resultSize.Height = sideLength;

    return resultSize;
}

protected override Size ArrangeOverride(Size finalSize)
{
    ((UIElement)Content).Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
    return finalSize;
}

我知道我必须在UserControl的每个孩子上调用MeasureArrange。由于DocPanel是我UserControl的唯一子项,并且(根据我的理解)存储在UserControl的Content属性中,因此我只需在此Content属性上调用MeasureArrange。但是不显示UserControl。我做错了什么?

1 个答案:

答案 0 :(得分:3)

根据您托管UserControl的方式,可能不会使用从测量阶段返回的值。如果您在具有星形行/列或DockPanel的网格中进行设置,则最终大小可能完全不同。

您需要对排列阶段应用类似的逻辑,因此它将有效地忽略它给出的任何额外空间。

以下代码应该有效,并且更清洁:

protected override Size MeasureOverride(Size availableSize) {
    var desiredSize = base.MeasureOverride(availableSize);
    var sideLength = Math.Min(desiredSize.Width, desiredSize.Height);

    desiredSize.Width = sideLength;
    desiredSize.Height = sideLength;

    return desiredSize;
}

protected override Size ArrangeOverride(Size finalSize) {
    var sideLength = Math.Min(this.DesiredSize.Width, this.DesiredSize.Height);
    return base.ArrangeOverride(new Size(sideLength, sideLength));
}