WPF利用通过父控件属性来获得绑定数据源RelativeSource

时间:2023-03-09 05:33:41
WPF利用通过父控件属性来获得绑定数据源RelativeSource

有时候我们不确定作为数据源的对象叫什么名字,但知道作为绑定源与UI布局有相对的关系,如下是一段XAML代码,说明多层布局控件中放置一个文本控件,来显示父级控件的名称。

1、XAML

  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"/>
  6. </DockPanel>
  7. </Grid>
  8. </DockPanel>
  9. </Grid>

2、后台代码

  1. RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
  1. //设定为离自己控件最近的第二层父控件
  2. rs.AncestorLevel = 2;
  1. //设定父控件为Gird类型
  2. rs.AncestorType = typeof(Grid);
  1. //绑定源为Grid的名称
  2. Binding binding = new Binding("Name") { RelativeSource=rs};
  1. //将绑定的源放在文本显示内容中
  2. this.textBox1.SetBinding(TextBox.TextProperty, binding);

3、以上后台代码等同于XAML中的

  1. <TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=2},Path=Name}"/>