Thursday, June 5, 2008

Two names of a single element

It turned out that one element in WPF can have two (or even more!) names. For example you create UserControl, and add it to the Window. Like that:

<Window>
    <MyControl Name="Control1"/>
</Window>

And inside the control (I mean the XAML file that defines the control) you make a Binding to the control itself, so you need to specify the ElementName. Like that:

<MyControl Name="Root">
    <TextBlock Text="{Binding Path=Property1, ElementName=Root}"/>
</MyControl>

So, as you can see, MyControl element has two different names at the same time: Control1 and Root. But how is it possible? The answer will be like following: Different name scopes (I mean NameScope class that implements INameScope interface).

So how did we get two different name scopes for a single element? The secret is that when the UserControl is defined in XAML, and it's XAML definition is loaded, new name scope is created for the control automatically, and all names, that are set inside the control's XAML file or inside its visual tree, goes to its own name scope. And the name, defined in a window definition (like Control1 ), is registered in a windows name scope.

So that is all the magic you need :)