"
AncestorLevel
"用于查找正确的祖先元素进行绑定,这是因为可能会存在多个相同类型的祖先元素。
以下是一个说明此情况的场景:
<Grid Tag="AncestorLevel 3">
<Grid Tag="AncestorLevel 2">
<Grid Tag="AncestorLevel 1">
<StackPanel Tag="StackPanel Tag" Height="100" HorizontalAlignment="Left" Margin="156,97,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="200">
<Label Content="{Binding Path=Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Grid},FallbackValue=BindingFailed}" Height="28" />
<Label Content="{Binding Path=Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=2,AncestorType=Grid},FallbackValue=BindingFailed}" Height="28" />
<Label Content="{Binding Path=Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=3,AncestorType=Grid},FallbackValue=BindingFailed}" Height="28" />
</StackPanel>
</Grid>
</Grid>
</Grid>
结果:
替代方法
但是您可以使用ElementName
绑定来简化代码,这将使用元素的Name
例如:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name="MyWindow" Tag="This is the window">
<Grid Name="Grid1" Tag="First grid">
<Grid Name="Grid2" Tag="Second grid">
<Grid Name="Grid3" Tag="ThirdGrid">
<StackPanel Name="stackPanel1" Tag="StackPanel Tag" Height="160" HorizontalAlignment="Left" Margin="156,97,0,0" VerticalAlignment="Top" Width="200">
<Label Content="{Binding ElementName=MyWindow, Path=Tag}" Height="28" />
<Label Content="{Binding ElementName=Grid1, Path=Tag}" Height="28" />
<Label Content="{Binding ElementName=Grid2, Path=Tag}" Height="28" />
<Label Content="{Binding ElementName=Grid3, Path=Tag}" Height="28" />
<Label Content="{Binding ElementName=stackPanel1, Path=Tag}" Height="28" />
</StackPanel>
</Grid>
</Grid>
</Grid>
</Window>
结果:
如果您想绑定回到
Window
,您仍然可以使用
FindAncestor
。
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Tag="This is the window">
<Grid>
<StackPanel Height="100" HorizontalAlignment="Left" Margin="156,97,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="200">
<Label Content="{Binding Path=Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window},FallbackValue=BindingFailed}" Height="28" />
</StackPanel>
</Grid>
结果:
Content = "{Binding Path = Tag,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = Window}
在这里运行良好。 - sa_ddam213