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

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

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

 

[html] view plain copy
 
  1. <Grid x:Name="g1" Background="Red" Margin="10">  
  2.     <DockPanel x:Name="d1" Background="Orange" Margin="10">  
  3.         <Grid x:Name="g2" Background="Yellow" Margin="10">  
  4.             <DockPanel x:Name="d2" Background="LawnGreen" Margin="10">  
  5.                 <TextBox x:Name="textBox1" FontSize="24" Margin="10"></TextBox>  
  6.             </DockPanel>  
  7.         </Grid>  
  8.     </DockPanel>  
  9. </Grid>  


界面截图:

 

 

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

 

[csharp] view plain copy
 
  1. RelativeSource rs = new RelativeSource();  
  2. rs.Mode = RelativeSourceMode.FindAncestor;  
  3. rs.AncestorLevel = 1;  
  4. rs.AncestorType = typeof(Grid);  
  5.   
  6. Binding binding = new Binding();  
  7. binding.RelativeSource = rs;  
  8. binding.Path = new PropertyPath("Name");  
  9. textBox1.SetBinding(TextBox.TextProperty, binding);  


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

 

 

与之等价的XAML代码是

 

[html] view plain copy
 
    1. Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type Grid}}, Path=Name}"  

posted on 2017-07-26 09:15  alex5211314  阅读(116)  评论(0编辑  收藏  举报

导航