You are confusing the WPF logical tree with how names are handled in XAML. In the logical tree the Polygon
is contained in the Grid
. However, all names belong to the same scope and are available as fields in the class generated from the XAML.
However, WPF has the concept of Namescopes which makes it possible to use the same name in multiple scopes.
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.
In the simple XAML below you have a Grid
named grid
containing a ListBox
named listBox
. In the class generated from the XAML there are fields named grid
and listBox
allowing the code behind to access both controls.
Each list box item generated by the ItemTemplate
contains a TextBlock
named textBlock
. However, each list box item is in a separate Namescope and there is no field named textBlock
in the class generated from the XAML.
<Grid x:Name="grid">
<ListBox x:Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="textBlock" Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
In this simple example there is no need to name the TextBlock
objects. However, in more advanced scenarios you may want to refer to named elements within the template, e.g. in triggers.