How does WPF solve same ElementName issues?

119 Views Asked by At

Say the following HierarchicalDataTemplate displays 2 Data Sets. Then there a 2 ListBoxes with the same x:Name ="MyListBoxName". How does WPF knows which one to pass as CommandParameter ????

<HierarchicalDataTemplate ItemsSource="{Binding SubNodes}">
      <ListBox x:Name="MyListBoxName">
      <i:Interaction.Triggers>
       <i:EventTrigger EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}, Path=DataContext.SelectedCommand}" CommandParameter="{Binding ElementName=MyListBoxName}"/>
       </i:EventTrigger>
      </i:Interaction.Triggers>
    </HierarchicalDataTemplate>

Thanks :)

3

There are 3 best solutions below

0
Steve On BEST ANSWER

WPF uses something similar to a bubbling event when resolving the name.

Since it finds an element with the name MyListBoxName within its immediate parent template it will use that one.

If not it will try to find it in the parent template's parent template and so on.

This is why in your case it compiles and works perfectly but fails if you try to add duplicated name within the same template

2
N_tro_P On

It doesn't, so I do not believe this works.

Why are you passing a UI element as the parameter to the datacontext anyways? I am guessing you can do what you are wanting but just need to think about it differently.

0
Bradley Uffner On

WPF uses Namescopes to partition names where there could be collisions.

Just as the visual-tree contains a tree of elements, There is a tree of namescopes built from the visual tree that defines a hierarchy of named elements. It prevents collisions within the same scope, and allows searching through nested scopes for named elements.

Styles and templates in WPF provide the ability to reuse and reapply content in a straightforward way. However, styles and templates might also include elements with XAML names defined at the template level. That same template might be used multiple times in a page. For this reason, styles and templates both define their own XAML namescopes, independent of whatever location in an object tree where the style or template is applied.

The full article goes pretty deep in to the details of how names are resolved within regular namescopes, and nested scopes, including those within styles and templates.