1. 前言

这篇文章介绍wpf ui元素的两步布局过程,并且通过resizer控件介绍只使用measure可以实现些什么内容。

我不建议初学者做太多动画的工作,但合适的动画可以引导用户视线,提升用户体验。例如上图的这种动画,这种动画挺常见的,在内容的高度改变时动态地改变自身的高度,除了好看以外,对用户体验也很有改善。可惜的是wpf本身没有默认这种这方面的支持,连expander的展开/折叠都没有动画。为此我实现了一个可以在内容大小改变时以动画的方式改变自身大小的resizer控件(想不到有什么好的命名,请求建议)。其实老老实实从silverlight toolkit移植accordionitem就好,但我想通过这个控件介绍一些布局(及动画)的概念。resizer使用方式如下xaml所示:

<stackpanel>
    <kino:kinoresizer horizontalcontentalignment="stretch">
        <expander header="expander1">
            <rectangle height="100"
                       fill="red" />
        </expander>
    </kino:kinoresizer>
    <kino:kinoresizer horizontalcontentalignment="stretch">
        <expander header="expander2">
            <rectangle height="100"
                       fill="blue" />
        </expander>
    </kino:kinoresizer>
</stackpanel>

2. 需要了解的概念

为了实现这个控件首先要了解wpf ui元素的布局过程。

2.1 两步布局过程

wpf的布局大致上分为measure和arrange两步,布局元素首先递归地用measure计算所有子元素所需的大小,然后使用arrange实现布局。

以stackpanel为例,当stackpanel需要布局的时候,它首先会得知有多少空间可用,然后用这个可用空间询问children的所有子元素它们需要多大空间,这是measure;得知所有子元素需要的空间后,结合自身的布局逻辑将子元素确定实际尺寸及安放的位置,这是arrange。

当stackpanel需要重新布局(如stackpanel的大小改变),这时候stackpanel就重复两步布局过程。如果stackpanel的某个子元素需要重新布局,它也会通知stackpanel需要重新布局。

2.2 measureoverride

measureoverride在派生类中重写,用于测量子元素在布局中所需的大小。简单来说就是父元素告诉自己有多少空间可用,自己再和自己的子元素商量后,把自己需要的尺寸告诉父元素。

2.3 desiredsize

desiredsize指经过measure后确定的期待尺寸。下面这段代码演示了如何使用measureoverride和desiredsize:

protected override size measureoverride(size availablesize)
{
    size paneldesiredsize = new size();

    // in our example, we just have one child. 
    // report that our panel requires just the size of its only child.
    foreach (uielement child in internalchildren)
    {
        child.measure(availablesize);
        paneldesiredsize = child.desiredsize;
    }

    return paneldesiredsize ;
}

2.4 invalidatemeasure

invalidatemeasure使元素当前的布局测量无效,并且异步地触发重新测量。

2.5 ismeasurevalid

ismeasurevalid指示布局测量返回的当前大小是否有效,可以使用invalidatemeasure使这个值变为false。

3. 实现

resizer不需要用到arrange,所以了解上面这些概念就够了。resizer的原理很简单,reszier的controltemplate中包含一个contentcontrol(innercontentcontrol),当这个innercontentcontrol的大小改变时请求resizer重新布局,resizer启动一个storyboard,以innercontentcontrol.desiredsize为最终值逐渐改变resizer的contentheight和contentwidth属性:

doubleanimation heightanimation;
doubleanimation widthanimation;
if (animation != null)
{
    heightanimation = animation.clone();
    storyboard.settarget(heightanimation, this);
    storyboard.settargetproperty(heightanimation, new propertypath(contentheightproperty));

    widthanimation = animation.clone();
    storyboard.settarget(widthanimation, this);
    storyboard.settargetproperty(widthanimation, new propertypath(contentwidthproperty));
}
else
{
    heightanimation = _defaultheightanimation;
    widthanimation = _defaultwidthanimation;
}

heightanimation.from = actualheight;
heightanimation.to = innercontentcontrol.desiredsize.height;
widthanimation.from = actualwidth;
widthanimation.to = innercontentcontrol.desiredsize.width;

_resizingstoryboard.children.clear();
_resizingstoryboard.children.add(heightanimation);
_resizingstoryboard.children.add(widthanimation);

contentwidth和contentheight改变时调用invalidatemeasure()请求重新布局,measureoverride返回contentheight和contentwidth的值。这样resizer的大小就根据storyboard的进度逐渐改变,实现了动画效果。

protected override size measureoverride(size constraint)
{
    if (_isresizing)
        return new size(contentwidth, contentheight);

    if (_isinnercontentmeasuring)
    {
        _isinnercontentmeasuring = false;
        changesize(true);
    }

    return base.measureoverride(constraint);
}

private void changesize(bool useanimation)
{
    if (innercontentcontrol == null)
    {
        return;
    }

    if (useanimation == false)
    {
        contentheight = innercontentcontrol.actualheight;
        contentwidth = innercontentcontrol.actualwidth;
    }
    else
    {
        if (_isresizing)
        {
            resizingstoryboard.stop();
        }

        _isresizing = true;
        resizingstoryboard.begin();
    }
}

用resizer控件可以简单地为expander添加动画,效果如下:

最后,resizer还提供doubleanimation animation属性用于修改动画,用法如下:

<kino:kinoresizer horizontalcontentalignment="stretch">
    <kino:kinoresizer.animation>
        <doubleanimation begintime="0:0:0"
                         duration="0:0:3">
            <doubleanimation.easingfunction>
                <quinticease easingmode="easeout" />
            </doubleanimation.easingfunction>
        </doubleanimation>
    </kino:kinoresizer.animation>
    <textbox acceptsreturn="true"
             verticalscrollbarvisibility="disabled" />
</kino:kinoresizer>

4. 结语

resizer控件我平时也不会单独使用,而是放在其它控件里面,例如button:

由于这个控件性能也不高,以后还可能改进api,于是被放到了primitives命名空间。

很久很久以前常常遇到“布局循环”这个错误,这常常出现在处理布局的代码中。最近很久没遇到这个错误,也许是wpf变健壮了,又也许是我的代码变得优秀了。但是一朝被蛇咬十年怕草绳,所以我很少去碰measure和arrange的代码,我也建议使用measure和arrange要慎重。

5. 参考

frameworkelement.measureoverride(size) method (system.windows) microsoft docs.html

uielement.desiredsize property (system.windows) microsoft docs.html

uielement.invalidatemeasure method (system.windows) microsoft docs

uielement.ismeasurevalid property (system.windows) microsoft docs

6. 源码

kino.toolkit.wpf_resizer at master