WPF利用通過父控件屬性來獲得綁定數據源RelativeSource

有時候我們不確定作爲數據源的對象叫什麼名字,但知道作爲綁定源與UI佈局有相對的關係,如下是一段XAML代碼,說明多層佈局控件中放置一個文本控件,來顯示父級控件的名稱。

1、XAML

 <Grid x:Name="g1" Background="Red" Margin="10">
        <DockPanel x:Name="d1" Background="Orange" Margin="10">
            <Grid x:Name="g2" Background="Yellow" Margin="10">
                <DockPanel x:Name="d2" Background="LawnGreen" Margin="10">
                    <TextBox x:Name="textBox1" FontSize="24" Margin="10"/>
                </DockPanel>
            </Grid>
        </DockPanel>
    </Grid>

2、後臺代碼

 RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
//設定爲離自己控件最近的第二層父控件
 rs.AncestorLevel = 2;
//設定父控件爲Gird類型
 rs.AncestorType = typeof(Grid);
//綁定源爲Grid的名稱
 Binding binding = new Binding("Name") { RelativeSource=rs};
//將綁定的源放在文本顯示內容中
 this.textBox1.SetBinding(TextBox.TextProperty, binding);

3、以上後臺代碼等同於XAML中的

 <TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=2},Path=Name}"/>


發佈了93 篇原創文章 · 獲贊 58 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章