Sunday, April 18, 2010

Flattening structure for Hierarchical display


I’ve been dealing before with HierarchicalDataTemplate where one Template references another one for 2 level hardcoded data structure. What about data that recursively references several types of “children”. Plus each type shows itself uniquely. How to visualize this ?

See tree screenshot as an example. In this example we have 3 data types: Drive, Folder, Files. Drive is a top level. Folder references Folder and Files.

Here is an overview of relationships between TreeView and Data Templates.

We need 2 things: DataTemplateSelector and “HierarchyConverter”.

HierarchyConverter is IValueConverter. HierarchyConverter parses through given object and returns “Children”, one level after another.

DataTemplateSelector returns a HierarchicalDataTemplate based on given object Type. Similar object types that were handled in HierarchyConverter. DataTemplateSelector is assigned to ItemTemplateSelector.

Each data type has an appropriate HierarchicalDataTemplate. Top level data template(Drive in our example) engages DataTemplateSelector. And all data types engage HierarchyConverter.

Top Level Template:

<HierarchicalDataTemplate x:Key="DriveTemplate"
ItemTemplateSelector="{StaticResource TreeTemplateSelector}"
ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">

The rest of levels follow similar format:

<HierarchicalDataTemplate x:Key="FolderTemplate"  DataType="{x:Type Framework:Folder}"

                       ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">

And to start it with your favorite Tree View:       <my:CustomTreeView Name="MyTree" ItemTemplate="{StaticResource DriveTemplate}"             

Let’s try to summarize data flow here. TreeView accepts data and streams to DriveTemplate. DriveTemplate sticks around until Folder in means of HierarchyConverter, while engaging TemplateSelector. At that time, different DataTemplates are activated which again engage recursive nature of HierarchyConverter.


Post a Comment