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

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

当一个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}"


猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9080453.html
今日推荐