WPF 使用RelativeSource绑定
在WPF绑定的时候,指定绑定源时,有一种办法是使用RelativeSource。
这种办法的意思是指当前元素和绑定源的位置关系。
第一种关系: Self
举一个最简单的例子:在一个StackPanel中,有一个TextBlock。
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>
如果想让textbox的width和height相同,通过设置属性Height=“{Binding RelativeSource={RelativeSource Self},Path=Width}” 就可以实现。
第二种关系:TemplatedParent
例如为一个Button写一个样式,修改Button为椭圆型。同时需要椭圆的背景色和Button的背景色相同。
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
</Ellipse.Fill>
</Ellipse>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
在这个例子中 TemplateParent就是指的Button
第三种关系:AncestorType
指定绑定源为某个父元素
<Grid>
<Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>
</Grid>
这个例子中Label的背景色和Grid的背景色一样。
FindAncestor模式
FindAncestor:引用数据绑定元素父链中的上级。 您可以使用它绑定到特定类型或其子类的上级。 如果您要指定 AncestorType 和/或 AncestorLevel,可以使用此模式 ;
AncestorType 获取或设置要查找的上级节点的类型。如果未显式设置 Mode 属性,那么设置 AncestorType 或 AncestorLevel 属性将把 Mode 属性值隐式锁定为 FindAncestor。
<Grid x:Name="g1" Background="Red" Margin="10">
<DockPanel Name="d1" Background="Orange" Margin="10">
<Grid x:Name="g2" Background="Yellow" Margin="10">
<DockPanel Name="d2" Background="LawnGreen" Margin="10">
<TextBox Name="textbox" FontSize="24" Margin="10"
Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1},Path=Name}"/>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
RelativeSource属性的数据类型为RelativeSource类,AncestorLevel指的是以Bingding目标控件为起点的层级偏移量,d2的偏移量是1,g2的偏移量是2,AncestorType指的是要找的目标对象的类型。值得注意的是AncestorLevel需要参考AncestorType使用,如上面设置了AncestorType={x:Type Grid},则Bingding在寻找时会忽略非Grid的控件,此时g2的偏移量是1,g1的偏移量是2,DockPanel被忽略。