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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM