码迷,mamicode.com
首页 > 其他好文 > 详细

数据绑定(八)使用Binding的RelativeSource

时间:2015-03-20 12:37:50      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

当一个Binding有明白的数据来源时能够通过为Source或ElementName赋值的办法让Binding与之关联,有的时候因为不能确定Source的对象叫什么名字,但知道它与作为Binding目标的对象在UI布局上有相对关系,比方控件自己关联自己的某个数据、关联自己某级容器的数据,就要使用Binding的RelativeSource属性。RelativeSource属性的数据类型为RelativeSource类,通过这个类的几个静态或非静态属性能够控制它搜索相对数据源的方式。

以下这个界面是在多层布局控件中放置着一个TextBox

    <Grid x:Name="g1" Background="Red" Margin="10">
        <DockPanel x:Name="d1" Background="Orange" Margin="10">
            <Grid x:Name="g2" Background="Yellow" Margin="10">
                <DockPanel x:Name="d2" Background="LawnGreen" Margin="10">
                    <TextBox x:Name="textBox1" FontSize="24" Margin="10"></TextBox>
                </DockPanel>
            </Grid>
        </DockPanel>
    </Grid>

界面截图:

技术分享


使用例如以下代码,将TextBox控件向外,从第一层開始寻找,找到的第一个Grid对象的Name与TextBox控件绑定

            RelativeSource rs = new RelativeSource();
            rs.Mode = RelativeSourceMode.FindAncestor;
            rs.AncestorLevel = 1;
            rs.AncestorType = typeof(Grid);

            Binding binding = new Binding();
            binding.RelativeSource = rs;
            binding.Path = new PropertyPath("Name");
            textBox1.SetBinding(TextBox.TextProperty, binding);

AncestorLevel属性指的是以Binding目标控件为起点的层级偏移量,d2的偏移量是1,g2的偏移量是2,以此类推,AncestorType属性告诉Binding寻找哪个类型的对象作为自己的源,不是这个类型的对象会被跳过


与之等价的XAML代码是

Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type Grid}}, Path=Name}"


数据绑定(八)使用Binding的RelativeSource

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4353306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!