WPF RelativeSource
<Window x:Class="WpfDemo.RelativeSourceDemo" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="RelativeSourceDemo" Height="300" Width="300"> <Grid x:Name="G1"> <StackPanel x:Name="S1"> <Grid Margin="20" x:Name="G2"> <StackPanel x:Name="S2"> <TextBox Margin="20" x:Name="textBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel},AncestorLevel=1},Path=Name}" Height="150" ToolTip="1111"/> </StackPanel> </Grid> </StackPanel> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfDemo { /// <summary> /// RelativeSourceDemo.xaml 的交互逻辑 /// </summary> public partial class RelativeSourceDemo : Window { public RelativeSourceDemo() { InitializeComponent(); //当有明确的数据源时,我们通过 source=。。。 绑定数据 //但是如果没有明确的对象名称,但是知道 这个对象 与绑定的对象在UI布局上有对象关系 //RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor); //rs.AncestorLevel = 1; //rs.AncestorType=typeof(Grid); //// 从自己的第一层向外寻找 第一个 Grid 对象 //this.textBox.SetBinding(TextBox.TextProperty, new Binding("Name") { RelativeSource = rs });//G2 //或者XAML 里面绑定 // Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1},Path=Name}" //rs.AncestorLevel = 2; //rs.AncestorType = typeof(Grid); //// 从自己的第一层向外寻找 第一个 Grid 对象 //this.textBox.SetBinding(TextBox.TextProperty, new Binding("Name") { RelativeSource = rs });//G1 // 同时 还可以绑定自身的属性 RelativeSource rs = new RelativeSource(RelativeSourceMode.Self); this.textBox.SetBinding(TextBox.TextProperty, new Binding("Name") { RelativeSource = rs }); } } }