WPF MeasureOverride对我的自定义控件不起作用

本文关键字:自定义控件 不起作用 我的 MeasureOverride WPF | 更新日期: 2023-09-27 18:04:01

我有一个自定义控件,它被"托管"在一个自定义面板中。

我的自定义面板代码如下:

protected override Size MeasureOverride(Size availableSize)
{
  foreach (UIElement child in Children)
  {
     child.Measure(availableSize);
     // Do stuff with the Desired Size.  (This is an example)
     resultSize.Width += child.DesiredSize.Width;
     resultSize.Height = Math.Max(resultSize.Height, child.DesiredSize.Height);
  }
  //.. Other Measure Stuff
}

我在面板中放置的所有标准控件都可以正常工作。但是我的自定义控件将DesiredSize设置为非常小的宽度(5像素)。即使它上面有一个Label,它至少需要40像素才能显示。

所以我把这段代码放入我的自定义控件中:
protected override Size MeasureOverride(Size constraint)
{
    var baseSize = base.MeasureOverride(constraint);
    var labelTextWidth = GetStringWidth(label.Content.ToString(), label);
    if (baseSize.Width == 0)
        baseSize.Width = 100;
    if (baseSize.Width < labelTextWidth)
        baseSize.Width = labelTextWidth;
    return baseSize;
}

返回正确的Size。但在我的Panel的MeasureOverride中,孩子。DesiredSize不能反映我从子控件的MeasureOverride返回的内容。

知道为什么会这样吗?我该怎么做才能把我计算出来的尺寸正确地传递到DesiredSize的面板上呢?(不能只设置DesiredSize)

WPF MeasureOverride对我的自定义控件不起作用

如果自定义控件的MeasureOverride返回正确的大小,但它没有反映在DesiredSize属性中,我只有一个建议。你的子元素被某个容器包裹,你可以在自定义面板的MeasureOverride过程中检查子元素的类型