Different Binding RelativeSource Mode

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:

 

 

posted @ 2013-05-23 18:07  若愚Shawn  阅读(367)  评论(0编辑  收藏  举报