Different Binding RelativeSource Mode

本文详细介绍了WPF中四种相对源绑定模式:Self、FindAncestor、TemplatedParent及其实现方式。通过实例展示了如何使矩形的宽度始终等于其高度,并探讨了使用相对源绑定简化代码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4 kinds of RelativeSourcemode(MSDN)

Self:If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

  Imagine this case, a rectangle that we want that its height is always equal to its width, a square let's say. We can do this using the element name

1 <Rectangle Fill="Red" Name="rectangle" 
2                     Height="100" Stroke="Black" 
3                     Canvas.Top="100" Canvas.Left="100"
4                     Width="{Binding ElementName=rectangle,
5                     Path=Height}"/>
View Code

  But in this above case we are obliged to indicate the name of the binding object, namely the rectangle. We can reach the same purpose differently using the RelativeSource

1 <Rectangle Fill="Red" Height="100" 
2                    Stroke="Black" 
3                    Width="{Binding RelativeSource={RelativeSource Self},
4                    Path=Height}"/>
View Code

For that case we are not obliged to mention the name of the binding object and the Width will be always equal to the Height whenever the height is changed.

If you want to parameter the Width to be the half of the height then you can do this by adding a converter to the Binding markup extension. Let's imagine another case now

1 <TextBlock Width="{Binding RelativeSource={RelativeSource Self},
2                    Path=Parent.ActualWidth}"/>
View Code

The above case is used to tie a given property of a given element to one of its direct parent ones as this element holds a property that is called Parent. This leads us to another relative source mode which is the FindAncestor one.

FindAncestor: If you want to get a property on an ancestor:

{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

TemplatedParent: If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

Here's a more visual explanation in the context of a MVVM architecture:

 

 

转载于:https://www.cnblogs.com/shawnzxx/archive/2013/05/23/3095326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值