FrameworkElement.MeasureOverride Method
函数原型:
protected virtual Size MeasureOverride (Size availableSize)
假设A为父element,B为子elements集合中的一个元素。通过在FrameworkElement的子类中override这个方法来计算B所需要的空间。
参数:A提供的可用空间。
返回值:通过计算后确定的A所需的空间。
在override的MeasureOverride方法中要做以下3步:
- 对每一个B调用Measure方法。
- Measure方法调用完后,B的期望大小就保存在DesiredSize中了。
- 计算所有的DesiredSize的和,作为总的期望空间返回。
例如,VisualChildren里存放有所有的子元素:
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;
}
FrameworkElement.ArrangeOverride Method
函数原型:
protected virtual Size ArrangeOverride (
Size finalSize
)
参数: A所占的空间
返回值:A实际所用到的空间
通过在子类中override这个方法,实现为A中的所有子元素定位的目的。
例如:
protected override Size ArrangeOverride(Size finalSize)
{
foreach (UIElement child in VisualChildren)
{
double x = 50;
double y = 50;
child.Arrange(new Rect(new Point(x, y), child.DesiredSize));
}
return finalSize; // Returns the final Arranged size
}