views:

1715

answers:

3

What are the differences between making a binding self-referential via name versus self-referential via RelativeSource?

For example:

<!-- Self referential via name -->
<Window ...
        x:Name="This"
        DataContext="{Binding Path=Data, ElementName=This}" >

versus

<!-- Self referential via RelativeSource -->
<Window ...
        x:Name="This"
        DataContext="{Binding Path=Data, RelativeSource={RelativeSource Self}}" >

In my project they seem to behave identically, but I'm using them directly in a Window. This means that I immediately prefer the former because it's less typing.

Is the only advantage of RelativeSource its ability to be self-referential in (e.g.) a widely-used style? Or is there some additional semantic difference?

A: 

Why do you think that there is a difference between them? I think that they should be identical, since they are two ways of referring to the same element.

Andy
+4  A: 

Caveat: Not a WPF wizard

When you are binding directly onto a WPF element as in your example there is no difference. "This" is resolvable and will bind to the same item as Self.

My suspicion is the difference lies when you are binding via constructs such as Style. In that case what you actually want to bind to is the element the style is applied to. In this case RelativeSource Self will give you that element where "this" will just give you a the Style instance.

JaredPar
This was the only thing I could think of or find, also. I've run into lots of other questions re:WPF where I missed info,though, so I wanted to see if anyone else had something on this. Thanks, Jared. :)
Greg D
+1  A: 

If you tend to refactor the names of your controls a lot then using the self refrential form may be more desireable otherwise I would say it is a call I would make based on performance. Construct a small test and see which type of binding performs better and choose that one. If the performance difference is negligible then I would definitely take into consideration other maintainability considerations such as the overall appearance and time to type. Also don't forget, when using the self referential form you don't have to name your element so you have to include that extra naming requirement for the ElementName form when comparing how much typing and context switching between the mouse and keyboard.

Personally I prefer the referential binding forms when it makes sense for the purposes of easier refactoring and the fact that I don't have to move around my XAML document to add an element name when I set up the binding.

jpierson