6.3.12 使用Binding的RelativeSource
同一级控件知道名字前提下的绑定:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox x:Name="textBox1" Grid.Row="0" Margin="5"/>
<TextBox x:Name="textBox2" Grid.Row="1" Margin="5" Text="{Binding ElementName=textBox1, Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>有些时候我们不能确定作为Source的对象叫什么名字,但知道它与作为Binding目标的对象在UI布局上有相对关系,比如控件自己关联自己的某个数据,关联自己某级容器的数据。这时候我们就要使用Binding的RelativeSource属性。
<Grid x:Name="g1" Background="Orange" Margin="10">
<DockPanel x:Name="d1" Background="Yellow" Margin="10">
<Grid x:Name="g2" Background="LawnGreen" Margin="10">
<TextBox x:Name="textBox1" Margin="10"/>
</Grid>
</DockPanel>
</Grid> textBox1.SetBinding(TextBox.TextProperty, new Binding("Background")
{
RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DockPanel), ancestorLevel: 1)
}); <Grid x:Name="g1" Background="Orange" Margin="10">
<DockPanel x:Name="d1" Background="Yellow" Margin="10">
<Grid x:Name="g2" Background="LawnGreen" Margin="10">
<TextBox x:Name="textBox1" Margin="10"
Text="{Binding Path=Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=2}}"/>
</Grid>
</DockPanel>
</Grid>也可以关联控件本身自己,只要让Mode属性值设置为Self。
<Grid x:Name="g1" Background="Orange" Margin="10">
<DockPanel x:Name="d1" Background="Yellow" Margin="10">
<Grid x:Name="g2" Background="LawnGreen" Margin="10">
<TextBox x:Name="textBox1" Margin="10"
Text="{Binding Path=Name, RelativeSource={RelativeSource Mode=Self}}"/>
</Grid>
</DockPanel>
</Grid>
RelativeSource实例:
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type Window},Mode=FindAncestor}, Path=.Height}" Width="100" Height="50"/>
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type Window},Mode=FindAncestor}, Path=.Width}" Width="100" Height="50"/>
本文详细介绍了在WPF中使用RelativeSource属性进行控件间基于相对位置的绑定方法,包括同一级控件之间的绑定、关联控件本身及父级容器的数据。通过实例展示了如何灵活运用RelativeSource实例实现复杂的数据绑定需求。
1640

被折叠的 条评论
为什么被折叠?



