WPF綁定數據源之RelativeSource
有時候我們不確定作爲數據源的對象叫什麼名字,但知道作爲綁定源與UI佈局有相對的關係,如下是一段XAML代碼,說明多層佈局控件中放置一個文本控件,來顯示父級控件的名稱。
1、XAML
Html代碼:
<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、後臺代碼
Csharp代碼 :
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中的
Html代碼:
<TextBox x:Name="textBox1" FontSize="24" Margin="10" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=2},Path=Name}"/>
二.TemplatedParent
TemplatedParent是RelativeSource的其中一種方式,使用該方式將使源元素成爲模板目標類型—即TargetType;如果該綁定是在模板中,那麼它的作爲範圍也只限於該模板.
例:
<Style TargetType="{x:Type local:TemplatedParent}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TemplatedParent}">
<Grid>
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
</Ellipse.Fill>
</Ellipse>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
這樣綁定的源元素就指向local:TemplatedParent這個目標類型了,所以當你修改目標類型的背景顏色時,Ellipse也將跟隨它變化。
三.Self
<Window x:Class="WpfApplication1.chap5_2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="chap5_2" Height="300" Width="300">
<Grid>
<Slider Name="slider"
Margin="4" Interval="1"
TickFrequency="1"
IsSnapToTickEnabled="True"
Minimum="0" Maximum="100"
ToolTip="{Binding RelativeSource ={ RelativeSource Self}, Path=Value}"/>
</Grid>
</Window>
其中Binding RelativeSource={RelativeSource Self}等價於Binding RelativeSource={x:Static RelativeSource.Self}