gpt4 book ai didi

c# - WPF MeasureOverride 不适用于我的自定义控件

转载 作者:行者123 更新时间:2023-11-30 18:35:06 25 4
gpt4 key购买 nike

我有一个“托管”在自定义面板(都是我的面板)中的自定义控件。

我的自定义面板有这样的代码:

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。但是在我的面板的 MeasureOverride 中,child.DesiredSize 没有反射(reflect)我从子控件的 MeasureOverride 返回的内容。

知道为什么要这样做吗?我可以做些什么来让它在 DesiredSize 中正确地将我计算的 Measure 传递给面板?(你不能只设置 DesiredSize。)

最佳答案

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

关于c# - WPF MeasureOverride 不适用于我的自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com