wpf binding中的relativesource属性

一、简介

一个在binding中比较重要的知识点——relativesource. 使用relativesource对象指向源对象。用这个可以在当前元素的基础上查找其他对象用于绑定到源对象。
在实际使用binding的过程中大部分时间binding都放在了数据模板和控件模板中,(数据模板是控件模板用于定义控件的ui)。
在模板中编写binding时有时候无法直接拿到我们需要绑定的数据对象,我们不能确定我们需要的source对象叫什么,但是我们直到了我们需要使用的对象在ui布局上的相对关系。比如控件自己关联了某个数据,关键自己某个层级的容器数据。这个时候我们的relativesource就派上了用场。我们使用relativesource首先要3个关键参数。
ancestortype=我们需要查找的类型。比如grid
ancestorlevel= 我们需要向上查找几级。
path=我们找到的元素需要绑定的属性。

二、代码

 <!--嵌套grid-->
    <grid x:name="g0" margin="12" background="red">
        <textblock text="in this grid0 container"/>
        <grid x:name="g1" margin="12" background="blue">
            <textblock text="in this grid1 container"/>
            <grid x:name="g2" margin="12" background="yellow">
                <textblock text="in this grid2 container"/>
                <grid x:name="g3" margin="12" background="beige">
                    <stackpanel>
                        <textblock text="in this grid3 container"/>
                        <!--ancestortype=我们需要查找的类型。比如grid-->
                        <!--ancestorlevel= 我们需要向上查找几级-->
                        <!--path=我们找到的元素需要绑定的属性。-->
                        <textblock name="ces" text="{binding relativesource={relativesource ancestortype=grid,ancestorlevel=1},path=name}"/>
                    </stackpanel>
                </grid>
            </grid>
        </grid>
    </grid>

三、运行结果

我们嵌套几个grid,并在每个嵌套的grid中都放入了一行文本用来显示自己所在的位置。设置了margin使他有部分的重叠,可以更好的看到相互之间的层级关系。最内层使用一个textblock.在textblock的text属性上使用relativesource。通过修改ancestorlevel 来设置向上查找grid的等级。我们设置为1.向外层查找第一个找到的grid对象。并绑定对应的name。