XAML-defined DataTemplate has a VisualTree value of zero

I am using WPF with .NET 3.0.

I have a relatively simple DataTemplate defined as a CellTemplate for a GridView. I expect the VisualTree DataTemplate property to contain FrameworkElementFactory, but the property is null when I try to access it from the GridViewColumnHeader.Click event. Why is VisualTree null? I need to access it. Here is the definition of a ListView:

<ListView ItemsSource="{Binding Stuff}" GridViewColumnHeader.Click="Header_Click"> <ListView.View> <GridView> <GridViewColumn Width="28"> <GridViewColumn.CellTemplate> <DataTemplate> <Image Name="statusImage" Width="16" Height="16" Source="../Images/media_play_green_16x16.png"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> 

And here is the event handler:

 private void Header_Click(object sender, RoutedEventArgs e) { GridViewColumnHeader gvch = e.OriginalSource as GridViewColumnHeader; // error! VisualTree is null! //gvch.Column.CellTemplate.VisualTree.GetType(); } 
+4
source share
2 answers

This is a known and expected behavior. I can’t find MSDN or another "authoritative" quote right now, but this MSDN forum post explains (kind of!):

The FrameworkTemplate.VisualTree ... property is mainly used when you programmatically create a DataTemplate / ControlTemplate in code. When defining a DataTemplate / ControlTemplate using XAML, this property will be null because WPF uses a different mechanism to create and create XAML-created templates . (italics added)

Thus, the VisualTree property is not populated when the template is loaded from XAML: it is populated only if you create the template in code using FrameworkElementFactory.

To get the contents of a template defined in XAML, call FrameworkTemplate.LoadContent (). This will allow you to materialize the template instance and provide you with the root element - after that you can drill as needed and set properties or bindings. It is up to you to fold the materialized instance into the containing window or manage the visual tree, however, so you probably want to encapsulate it!

+6
source

The reason for the appearance of the Visual Tree is that the Visual Tree property is closer to the Logical Tree , not Visual One . The actual contents of the template are stored in a TemplateContent object that has no public members, you will need to use the LoadContent method.

0
source

Source: https://habr.com/ru/post/1305604/


All Articles