zoukankan      html  css  js  c++  java
  • 数据绑定(八)使用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}"


  • 相关阅读:
    Python--列表、元组
    python之helloworld
    JMeter添加压力机、下载文件
    JMeter接口测试
    Postman接口测试
    浅谈接口测试
    poj3974 最长回文串 exkmp
    GDOI2014 beyond(D2T3) exkmp
    hdu4333 扩展KMP
    poj 3080 KMP
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4544380.html
Copyright © 2011-2022 走看看