语言

FrameworkElement.MeasureOverride(Size) 方法

定义

在派生类中重写时,测量子元素所需的布局大小,并确定派生类的大小 FrameworkElement。

protected:
 virtual System::Windows::Size MeasureOverride(System::Windows::Size availableSize);
protected virtual System.Windows.Size MeasureOverride(System.Windows.Size availableSize);
abstract member MeasureOverride : System.Windows.Size -> System.Windows.Size
override this.MeasureOverride : System.Windows.Size -> System.Windows.Size
Protected Overridable Function MeasureOverride (availableSize As Size) As Size

参数

availableSize
Size

此元素可以提供给子元素的可用大小。 可以将 Infinity 指定为一个值,以指示元素将大小调整为任何可用内容。

返回

此元素根据子元素大小的计算来确定它在布局期间所需的大小。

注解

重写 MeasureOverride,以便在元素参与Windows Presentation Foundation(WPF)布局系统时实现自定义布局大小调整行为。 实现应执行以下操作:

  1. 循环访问属于布局的子元素的特定集合,对每个子元素进行调用 Measure 。

  2. 立即启动 DesiredSize 子级(在调用后 Measure 将其设置为属性)。

  3. 根据子元素的度量计算父级的净所需大小。

返回值 MeasureOverride 应为元素自己的所需大小,然后成为当前元素的父元素的度量值输入。 在到达页面的根元素之前,这一过程将继续执行布局系统。

在此过程中,子元素可能会返回比初始DesiredSize元素更大的availableSize大小,以指示子元素需要更多空间。 这可以通过引入可滚动区域、调整父控件的大小、建立某种堆积顺序或任何数量的用于测量或排列内容的解决方案,在你自己的实现中进行处理。

Important

在此过程中,元素应调用 Measure 每个子元素,否则子元素的大小不正确或排列。

继承者说明

以下非编译代码显示此实现模式。 VisualChildren 表示你自己的元素应定义的子项的可枚举集合属性。 该属性可以命名为任何内容。 VisualChildren是此示例的占位符名称,VisualChildren不是由WPF或命名模式的一部分提供的 API。

protected override Size MeasureOverride(Size availableSize)
{
    Size desiredSize = new Size();
    foreach (UIElement child in VisualChildren)
    {
        child.Measure(availableSize);
        // do something with child.DesiredSize, either sum them directly or apply whatever logic your element has for reinterpreting the child sizes
        // if greater than availableSize, must decide what to do and which size to return
    }
    // desiredSize = ... computed sum of children's DesiredSize ...;
    // IMPORTANT: do not allow PositiveInfinity to be returned, that will raise an exception in the caller!
    // PositiveInfinity might be an availableSize input; this means that the parent does not care about sizing
    return desiredSize;
}
Protected Overrides Function MeasureOverride(ByVal availableSize As Size) As Size
    Dim desiredSize As New Size()
    For Each child As UIElement In VisualChildren
        child.Measure(availableSize)
        ' do something with child.DesiredSize, either sum them directly or apply whatever logic your element has for reinterpreting the child sizes
        ' if greater than availableSize, must decide what to do and which size to return
    Next child
    ' desiredSize = ... computed sum of children's DesiredSize ...
    ' IMPORTANT: do not allow PositiveInfinity to be returned, that will raise an exception in the caller!
    ' PositiveInfinity might be an availableSize input - this means that the parent does not care about sizing
    Return desiredSize
End Function

适用于