【WPF】WPF通过RelativeSource绑定父控件的属性
1.后台代码实现绑定父控件的属性
RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor); //设定为离自己控件最近的第一层父控件 rs.AncestorLevel = 1; //设定父控件为Gird类型 rs.AncestorType = typeof(Grid); //绑定源为Grid的名称 Binding binding = new Binding("Name") { RelativeSource=rs}; //将绑定的源放在文本显示内容中 this.textBox1.SetBinding(TextBox.TextProperty, binding);
2.前台xaml实现绑定父控件的属性
<TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1},Path=Name}"/>