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. CallingFindName
on an element searches only the NameScope in which the element was originally generated. Hence callingFindName
on theUserControl
will 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 theVisualTreeEnumeration
class from that blog added to your project you can do this:-Of course if you know that "stack" is a
StackPanel
then you can get more specific with.OfType<T>
.