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 DataTemplate
belongs to a different NameScope than the outer Xaml. Calling FindName
on an element searches only the NameScope in which the element was originally generated. Hence calling FindName
on the UserControl
will not find elements generated by a DataTemplate
. The reason for this is that DataTemplate
(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 on VisualTreeHelper
. With the VisualTreeEnumeration
class from that blog added to your project you can do this:-
var element = this.Descendents().OfType<FrameworkElement>().FirstOrDefault(fe => fe.Name == "stack");
Of course if you know that "stack" is a StackPanel
then you can get more specific with .OfType<T>
.