RelativeSource有四种类型

Self

FindAncestor

TemplatedParent

PreviousData

a.Self

Self用于绑定源和绑定目标相同的场景中。对象的一个属性与同一对象的另一个属性绑定。

例如,让我们取一个高度和宽度相同的椭圆。在XAML文件中添加下面给出的代码。宽度属性与高度属性相对绑定。

 
<Grid>
<Ellipse Width="{Binding RelativeSource={RelativeSource Self}, Path=Height}"
Height="100"
Fill="Black" />
</Grid>

b.FindAncestor

FindAncestor
顾名思义,当绑定源是绑定目标的祖先(父级)之一时使用此选项。使用FindAncestor扩展,可以找到任何级别的祖先。
             

现在,让我们使用FindAncestor扩展将祖先的Name属性绑定到子元素button的Content属性。

 
<Grid Name="Parent_3">
<StackPanel Name="Parent_222"
Width="100"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<StackPanel Name="Parent_2"
Width="100"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border Name="Parent_1">
<StackPanel x:Name="Parent_0"
Orientation="Vertical">
<!-- 下面这个按钮Content得到:Parent_2 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Name}" />
<!-- 下面这个按钮Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=1}, Path=Name}" />
<!-- 下面这个按钮Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}" />
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Grid>

c.TemplatedParent

TemplatedParent是一个属性,它使您能够创建一个包含少量未知值的控件模板。这些值取决于应用ControlTemplate的控件的属性。

 
<Window.Resources>
<ControlTemplate x:Key="template1">
<!--
在应用模板时,按钮的Background(Beige)与椭圆的Fill属性相对绑定,Content(Click me)与ContentPresenter的Content属性相对绑定。依赖值生效并给出以下输出。
-->
<Canvas>
<Ellipse Width="155"
Height="110"
Fill="Black" />
<Ellipse Width="150"
Height="100"
Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
<ContentPresenter Margin="35"
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />
</Canvas>
</ControlTemplate>
</Window.Resources>
 
<Button Height="0"
Margin="5"
Background="Beige"
Content="Click me"
FontSize="18"
Template="{StaticResource template1}" />

d.PreviousData

PreviousData这个用得很少,表示值相对于以前数据的变化。

最终效果图

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

woisking2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值