一個Binding有明確的數據來源 可以通過Source或ElementName賦值的方法讓Binding與之關聯
但是有的時候我們不能確定作為Source的對象叫什么名字,但知道它與作為Binding目標的對象在UI上有相對關系,比如:空間自己關聯自己的某個數據、關聯自己某級容器的數據
這個時候!我們就要使用Binding的RelativeSource屬性了!
看個小例子
<Window x:Class="Wpf.Relative6312xaml"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Wpf"mc:Ignorable="d"Title="Relative6312xaml" Height="200" Width="200"><Grid x:Name="g1" Background="LightPink" Margin="10"><DockPanel x:Name="d1" Background="LightBlue" Margin="10"><Grid x:Name="g2" Background="LightCoral" Margin="10"><DockPanel x:Name="d2" Background="LightGreen" Margin="10"><TextBox x:Name="textBox1" FontSize="24" Margin="10"></TextBox></DockPanel></Grid></DockPanel></Grid>
</Window>
效果圖是這個樣子的
把TextBox的Text屬性關聯到外層容器的Name屬性上 在XAML中插入代碼
<Window x:Class="Wpf.Relative6312xaml"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Wpf"mc:Ignorable="d"Title="Relative6312xaml" Height="200" Width="200"><Grid x:Name="g1" Background="LightPink" Margin="10"><DockPanel x:Name="d1" Background="LightBlue" Margin="10"><Grid x:Name="g2" Background="LightCoral" Margin="10"><DockPanel x:Name="d2" Background="LightGreen" Margin="10"><TextBox x:Name="textBox1" FontSize="24" Margin="10"Text="{Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type Grid},AncestorLevel=1}, Path=Name}"></TextBox></DockPanel></Grid></DockPanel></Grid>
</Window>
效果圖
也可以在窗體的構造器中創建RelativeSource的對象再進行Binding
RelativeSource FindAncestor:尋找TextBox的祖宗元素
AncestorLevel = 1;向外層找1層
AncestorType = {x: Type Grid}:尋找的類型為Grid類型