RelativeSource属性

 我们进行Bingding时,如果明确知道数据源的Name,就能用Source或者ElementName

进行绑定,但是有时候我们需要绑定的数据源可能没有明确的Name,此时我们就需要利

用Bingding的RelativeSource进行绑定,这种办法的意思是指当前元素和绑定源的位置关

系。

属性

1)控件关联自身的属性——Self

AncestorLevel

以 FindAncestor 模式获取或设置要查找的上级级别。 使用 1 指示最靠

近绑定目标元素的项。

AncestorType

获取或设置要查找的上级节点的类型。

Mode

获取或设置 RelativeSourceMode 值,该值描述相对于绑定目标的位置

的绑定源的位置。

PreviousData

获取一个静态值,该值用于返回为 RelativeSource 模式构造

的 PreviousData。

Self

获取一个静态值,该值用于返回为 RelativeSource 模式构造的 Self。

TemplatedParent

获取一个静态值,该值用于返回为 RelativeSource 模式构造

的 TemplatedParent。

<Window x:Class="RelativeSource.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="MainWindow" Height="350" Width="525">

<Grid>

<StackPanel>

1

2

3

4

5

67 <TextBox Height="30" Width="60" Name="Box1" Text="{Binding

RelativeSource={RelativeSource Mode=self},Path=Name }"/>

8 </StackPanel>

9 </Grid>

10 </Window>

上例是前台xaml写法,再看下后台怎么实现:

1 public MainWindow()

2 {

3 InitializeComponent();

4 System.Windows.Data.RelativeSource rs = new

System.Windows.Data.RelativeSource();

5 rs.Mode = RelativeSourceMode.Self;

6 Binding binding = new Binding("Name") { RelativeSource = rs };

7 this.Box1.SetBinding(TextBox.TextProperty, binding);

8 }

2)控件关联其父级容器的属性——AncestorType

1 <Window x:Class="RelativeSource.MainWindow"

2 

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

4 Title="MainWindow" Height="350" Width="525">

5 <Grid Name="G1">

6 <Grid Name="G2">

7 <StackPanel Name="S1">

8 <TextBox Height="30" Width="60" Name="Box1" Text="

{Binding RelativeSource={RelativeSource Mode=FindAncestor,

AncestorType={x:Type Grid}, AncestorLevel=2},Path=Name }"/>

9 </StackPanel>

10 </Grid>

11 </Grid>

12 </Window>

详细介绍下AncestorLevel,它指的是以Bingding目标控件为起点的层级偏移量,S1的偏

移量是1,G2的偏移量是2,G1是偏移量3,AncestorType指的是要找的目标对象的类

型。值得注意的是AncestorLevel必须参考AncestorType使用,如上面设置了AncestorType={x:Type Grid},则Bingding在寻找时会忽略非Grid的控件,此时G2的偏移

量是1,G1的偏移量是2,StackPanel被忽略。

3)控件关联模板的属性——TemplatedParent

1 <Window.Resources>

2 <Style TargetType="{x:Type Button}">

3 <Setter Property="Background" Value="Green"/>

4 <Setter Property="Template"> 

5 <Setter.Value>

6 <ControlTemplate TargetType="{x:Type Button}">

7 <Grid>

8 <Ellipse>

9 <Ellipse.Fill>

10 <SolidColorBrush Color="{Binding

Path=Background.Color,RelativeSource={RelativeSource

TemplatedParent}}"/>

11 </Ellipse.Fill>

12 </Ellipse>

13 </Grid>

14 </ControlTemplate>

15 </Setter.Value>

16 </Setter>

17 </Style>

18 </Window.Resources>

总结

从运用性上介绍了RelativeSource三种使用方法,目前就碰到三种,有新的会继续更。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值