Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between ElementName="<Me>" and RelativeSource self?

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?

like image 324
Greg D Avatar asked Mar 10 '09 15:03

Greg D


2 Answers

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.

like image 184
JaredPar Avatar answered Sep 21 '22 11:09

JaredPar


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.

like image 43
jpierson Avatar answered Sep 22 '22 11:09

jpierson