If I have the following XAML:
<toolkit:DataForm Height=”100″ x:Name=”form”>
<toolkit:DataForm.EditTemplate>
<DataTemplate>
<StackPanel Name=”stack”></StackPanel>
</DataTemplate>
</toolkit:DataForm.EditTemplate>
</toolkit:DataForm>
I can get a reference to “form” by this.FindName(“form”) from the View.
How can I get a reference to “stack”? FindName returns null.
The problem here is that the xaml content of a
DataTemplatebelongs to a different NameScope than the outer Xaml. CallingFindNameon an element searches only the NameScope in which the element was originally generated. Hence callingFindNameon theUserControlwill not find elements generated by aDataTemplate. The reason for this is thatDataTemplate(and other templates) are designed to be reused multiple times, the use of NameScope disambiguates the names.The solution is to invoke the help of the
VisualTreeHelper, have a look at the code in this blog for my take onVisualTreeHelper. With theVisualTreeEnumerationclass from that blog added to your project you can do this:-Of course if you know that “stack” is a
StackPanelthen you can get more specific with.OfType<T>.