I remember reading a couple of weeks ago that it sometimes doesn\'t work inside templates, and I recently tried to bind things in two different windows and it couldn\'t find the
Basically you need to be in the same name scope (read this). Most UI elements are in the same tree sharing the same name scope, however there can be breaks and barriers (styles/templates) and if you have abstract objects like DataGrid
columns they do not have a name scope at all.
I've been working with WPF long enough to guess when i'll run into problems and i know common areas but don't think there's an easy way to tell in all situations up-front.
if this is true, doesn't that mean that Binding ElementName should not work in templates at all? But then I definitely have some working bindings on ElementName within my templates.
Within is just fine, that is the same scope. The point here is that if you apply the template and they would not have their own scopes there would be conflicts.
e.g.
If we expand the ControlTemplate
you would get something like:
...
...
Obviously we would get a name conflict.
Same for DataTemplates
in ItemsControls
, if you name controls in the template that name would conflict with the same control instance in the applied template of other items.
On another note, you can bind from inside a template to the outside because logically there can only be one instance with that name or you can give them a distinct precedence based on how "close" the name scope is, e.g.