1. 程式人生 > >【WPF】WPF通過RelativeSource繫結父控制元件的屬性

【WPF】WPF通過RelativeSource繫結父控制元件的屬性

原文: 【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}"/>