WPF Binding中的RelativeSource属性

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。

posted @ 2021-06-29 09:34  码农阿亮  阅读(1905)  评论(0编辑  收藏  举报