Reputation: 36775
Is there a possibility to access the logical tree of a DataTemplate.
<DataTemplate x:Key="Test_DataTemplate">
<Grid >
<TextBlock>Test</TextBlock>
</Grid>
</DataTemplate>
For the above example, if I get the DataTemplate by FindResource("Test_DataTemplate")
, is it then possible to access the tree, to get for instance the TextBlock-control.
Please note, I dont want to access the visual tree of an itemscontrol that uses this DataTemplate. I want to access the tree of the DataTemplate itselfs.
Upvotes: 2
Views: 3133
Reputation: 29594
DataTemplate has a VisualTree property that let's you access the factory objects used to create the object when the template is applied, you can't access the actual TextBox in your example because it doesn't exist until the template is applied.
Update:
When you build the DataTemplate in code you do it using the VisualTree property, the VisualTree property holds the data needed to construct the visual tree when the template is used.
The VisualTree property does not refer to the template's actual visual tree (accessed by VisualTreeHelper) because the template doesn't have an actual visual tree - only the information needed to build one.
And by the way, just to make things a little bit more interesting, the content of the data template's VisualTree property is closer to the logical tree than to the visual one.
A little testing shows that when you load the template from XAML the VisualTree property is null and the actual content of the template is stored elsewhere, this "elsewhere" is a TemplateContent object and this object has no public members you can use.
So, in order to access the content of a template defined in XAML you have to use the template's LoadContent method to actually create the objects defined in the template and then use VisualTreeHelper or LogicalTreeHelper to explore the created objects.
(you can use reflections to look into the TemplateContent object - but this means you are relying on undocumented internal implementation details that you don't fully understand and can change between versions - so I wouldn't recommend it)
Upvotes: 3