1. 前言

a long time ago in a galaxy far, far away….微软在silverlight toolkit里提供了一个好用的visualtreeextensions,里面提供了一些查找visualtree的扩展方法。在那个时候(2009年),visualtreeextensions对我来说正好是个很棒的linq和扩展方法的示例代码,比那时候我自己写的findchildbyname之类的方法好用一万倍,所以我印象深刻。而且因为很实用,所以我一直在用这个类(即使是在wpf中),而这次我也把它添加到kino.wpf.toolkit中,可以在 这里 查看源码。

2. visualtreeextensions的功能

public static class visualtreeextensions
{
    /// 获取 visual tree 上的祖先元素
    public static ienumerable<dependencyobject> getvisualancestors(this dependencyobject element) { }

    /// 获取 visual tree 上的祖先元素及自身
    public static ienumerable<dependencyobject> getvisualancestorsandself(this dependencyobject element) { }

    /// 获取 visual tree 上的子元素
    public static ienumerable<dependencyobject> getvisualchildren(this dependencyobject element) { }

    /// 获取 visual tree 上的子元素及自身
    public static ienumerable<dependencyobject> getvisualchildrenandself(this dependencyobject element) { }

    /// 获取 visual tree 上的后代元素
    public static ienumerable<dependencyobject> getvisualdescendants(this dependencyobject element) { }


    /// 获取 visual tree 上的后代元素及自身
    public static ienumerable<dependencyobject> getvisualdescendantsandself(this dependencyobject element) { }

    /// 获取 visual tree 上的同级别的兄弟元素
    public static ienumerable<dependencyobject> getvisualsiblings(this dependencyobject element) { }

    /// 获取 visual tree 上的同级别的兄弟元素及自身.
    public static ienumerable<dependencyobject> getvisualsiblingsandself(this dependencyobject element) { }
}

visualtreeextensions封装了visualtreehelper并提供了各种查询visual tree的方法,日常中我常用到的,在wpf上也没问题的就是以上的功能。使用代码大致这样:

foreach (var item in this.getvisualdescendants().oftype<textblock>())
{
}

3.使用问题

visualtreeextensions虽然好用,但还是有些问题需要注意。

3.1 不要在onapplytemplate中使用

frameworkelement在生成当前模板并构造visual tree时会调用onapplytemplate函数,但这时候最好不要使用visualtreeextensions去获取visual tree中的元素。所谓的最好,是因为wpf、silverlight、uwp控件的生命周期有一些出入,我一时记不太清楚了,总之根据经验运行这个函数的时候可能visual tree还没有构建好,visualtreehelper获取不到子元素。无论我的记忆是否出错,正确的做法都是使用 gettemplatechild 来获取controltemplate中的元素。

3.2 深度优先还是广度优先

<stackpanel margin="8">
    <groupbox header="groupbox" >
        <textbox margin="8" text="firsttextbox"/>
    </groupbox>
    <textbox margin="8"
             text="secondtextbox" />
</stackpanel>

假设有如上的页面,执行下面这句代码:

this.getvisualdescendants().oftype<control>().firstordefault(c=>c.istabstop).focus();

这段代码的意思是找到此页面第一个可以接受键盘焦点的控件并让它获得焦点。直觉上firsttextbox是这个页面的第一个表单项,应该由它获得焦点,但getvisualdescendants的查找方法是广度优先,因为secondtextbox比firsttextbox深了一层,所以secondtextbox获得了焦点。

3.3 popup的问题

popup没有自己的visual tree,打开popup的时候,它的child和window不在同一个visual tree中。以combobox为例,下面是combobox的controltemplate中的主要结构:

<grid name="templateroot"
      snapstodevicepixels="true">
    <grid.columndefinitions>
        <columndefinition width="*" />
        <columndefinition minwidth="{dynamicresource {x:static systemparameters.verticalscrollbarwidthkey}}"
                          width="0" />
    </grid.columndefinitions>
    <popup name="part_popup" 
           allowstransparency="true"
           margin="1"
           placement="bottom"
           grid.columnspan="2"
           popupanimation="{dynamicresource {x:static systemparameters.comboboxpopupanimationkey}}"
           isopen="{binding isdropdownopen, mode=twoway, relativesource={relativesource templatedparent}}">
        <theme:systemdropshadowchrome x:name="shadow"
                                      color="transparent"
                                      maxheight="{templatebinding combobox.maxdropdownheight}"
                                      minwidth="{binding actualwidth, elementname=templateroot}">
           ...
        </theme:systemdropshadowchrome>
    </popup>
    <togglebutton name="togglebutton"/>
    <contentpresenter name="contentpresenter"/>
</grid>

在实时可视化树视图中可以看到有两个visualtree,而popup甚至不在里面,只有一个叫popuproot的类。具体可参考 popup 概述 这篇文档。

不过combobox的popup在逻辑树中是存在的,如果comboboxitem想获取combobox的visualtree的祖先元素,可以配合逻辑树查找。

3.4 查找根元素

getvisualancestors可以方便地查找各级祖先元素,一直查找到根元素,例如要找到根元素可以这样使用:

element.getvisualancestors().last()

但如果元素不在popup中,别忘了直接使用getwindow更快捷:

window.getwindow(element)

5. 其它方案

很多控件库都封装了自己的查找visualtree的工具类,下面是一些常见控件库的方案:

  • windowscommunitytoolkit的visualtree
  • extended wpf toolkit的visualtreehelperex
  • mahapps.metro的treehelper
  • modern ui for wpf (mui)的visualtreehelperex
  • winrt xaml toolkit 的visualtreehelperextensions

6. 结语

visualtreeextensions的代码很简单,我估计在uwp中也能使用,不过uwp已经在windowscommunitytoolkit中提供了一个新的版本,只因为出于习惯,我还在使用silverlight toolkit的版本。而且toolkit中的finddescendantbyname(this dependencyobject element, string name)让我回忆起了我当年抛弃的findchildbyname,一点都不优雅。

延续visualtreeextensions的习惯,多年来我都把扩展方法写在使用-extensions后缀命名的类里,不过我不记得有这方面的相关规范。

7. 参考

visualtreehelper class (system.windows.media) _ microsoft docs

frameworkelement.gettemplatechild(string) method (system.windows) microsoft docs

popup 概述 microsoft docs

8. 源码

visualtreeextensions.cs at master · dinochan_kino.toolkit.wpf