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}"/>
