有時候我們不確定作爲數據源的對象叫什麼名字,但知道作爲綁定源與UI佈局有相對的關係,如下是一段XAML代碼,說明多層佈局控件中放置一個文本控件,來顯示父級控件的名稱。
1、XAML
<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"/>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
2、後臺代碼
RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
//設定爲離自己控件最近的第二層父控件
rs.AncestorLevel = 2;
//設定父控件爲Gird類型
rs.AncestorType = typeof(Grid);
//綁定源爲Grid的名稱
Binding binding = new Binding("Name") { RelativeSource=rs};
//將綁定的源放在文本顯示內容中
this.textBox1.SetBinding(TextBox.TextProperty, binding);
3、以上後臺代碼等同於XAML中的
<TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=2},Path=Name}"/>