Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / WPF

Organizing Heterogeneous Data on a WPF TreeView

Rate me:
Please Sign up or sign in to vote.
4.93/5 (16 votes)
14 May 2009CPOL3 min read 89.7K   32   22
Converter-based solution to render and organize heterogeneous data through WPF's built-in TreeView control

Most WPF TreeView samples you see on the web are somewhat simplistic: While they may provide heterogeneous data, usually all childs of a given node are of the same type:

simpletree

However, more often than not, you’re running into more complex scenarios where additional structuring is necessary. Imagine your Farm class looks like this:

image

Accordingly, you might want to display that information according to the sketch below:

complextree

Note the difference: We want to organize the Animals and Crops collections within individual sub folders, while the "Farmer" node is a direct child of the "Farm" root node. From the control’s point of view, this means that the "Folder" nodes and the "Farmer" node are siblings.

Now, one solution to that very problem is ViewModel wrapper classes that optimize the business logic for your specific UI logic. This route does work very well for quite a few scenarios. However, sometimes, you just want to have a quick solution. I’ll try to provide one here…

My solution to that very problem requires the following ingredients:

  • A MultiBinding that allows you to combine different bindings.
  • A converter that helps us organizing the different bound collections into sub folders, where necessary.
  • And of course: Data templates that provide a visual representation of your bound data.

Let’s start with the bindings, which are declared within a HiearchicalDataTemplate. You can use a MultiBinding to retrieve all necessary data of a given Farm instance:

XML
<HierarchicalDataTemplate DataType="{x:Type local:Farm}">

  <!-- bind the different data sources -->
  <HierarchicalDataTemplate.ItemsSource>
    <MultiBinding>
      <Binding Path="Farmer" />
      <Binding Path="Animals" />
      <Binding Path="Crops" />
    </MultiBinding>
  </HierarchicalDataTemplate.ItemsSource>

  <TextBlock Text="{Binding Path=FarmName}" />

</HierarchicalDataTemplate> 

A MultiBinding always needs a converter of type IMultiValueConverter. Our converter has to provide the following functionality:

  • Allow binding of simple objects (Farmer), or collections (Animals, Crops).
  • Where necessary, put a bound child item or collection into a virtual container object that can serve as a "folder" when it comes to rendering.
  • Provide means to name (or even identify) a folder in order to simplify styling.
  • Render specific child items directly under the parent node (no subfolder).
  • Return everything as an object that can be bound to the TreeView.ItemsSource property.

I wrote a simple converter that performs these tasks. The initial declaration looks like this:

XML
<MultiBinding Converter="{StaticResource folderConverter}">
  <Binding Path="Farmer" />
  <Binding Path="Animals" />
  <Binding Path="Crops" />
</MultiBinding> 
…and it produces the following output:

image

Obviously, the data is being parsed and assigned to the "Farm" nodes, but we’re still lacking the desired structure (sub folders for animals and plants). However, this can easily be done by setting the ConverterParameter property:

XML
<MultiBinding Converter="{StaticResource folderConverter}"
              ConverterParameter=", Animals, Cultivated Plants">
  <Binding Path="Farmer" />
  <Binding Path="Animals" />
  <Binding Path="Crops" />
</MultiBinding> 

The converter parameter allows you to define folders for any of the items that are bound within the MultiBinding, while an empty string inserts a bound item directly under the root item. The converter parameter above produces the following output:

image

The tree now renders the farmers and four FolderItem instances. FolderItem is a very simple helper class that is used by the converter to store the bound Animals and Crops collections. It provides just two properties:

  • Name (the string that was defined through the converter parameter)
  • Items (the folder’s contents)

Currently, the tree does not know yet how to render a FolderItem class, which is why there’s just the name displayed. What’s missing here is an additional data template for FolderItem:

XML
<!-- data template for FolderItem instances -->
<HierarchicalDataTemplate DataType="{x:Type vm:FolderItem}"
                          ItemsSource="{Binding Path=Items}">

  <TextBlock Text="{Binding Path=Name}" />

</HierarchicalDataTemplate> 

This finally produces the desired output which matches the originally sketched presentation:

image

Simply delegating data organization to the SimpleFolderConverter allows us to individually structure heterogeneous data for our TreeView control with a very simplistic approach. Below is the complete XAML for the sample:

XML
<Window
  x:Class="Hardcodet.Farms.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:vm="clr-namespace:Hardcodet.Farms.ViewModel"
  xmlns:local="clr-namespace:Hardcodet.Farms.Model"
  Title="Window1"
  Height="300"
  Width="300">

  <Window.Resources>
    <vm:SimpleFolderConverter x:Key="folderConverter" />

    <!-- data template for Farm instances -->
    <HierarchicalDataTemplate DataType="{x:Type local:Farm}">

      <!-- bind the different data sources -->
      <HierarchicalDataTemplate.ItemsSource>
        <MultiBinding Converter="{StaticResource folderConverter}"
                      ConverterParameter=", Animals, Cultivated Plants">
          <Binding Path="Farmer" />
          <Binding Path="Animals" />
          <Binding Path="Crops" />
        </MultiBinding>
      </HierarchicalDataTemplate.ItemsSource>

      <TextBlock Text="{Binding Path=FarmName}" />
    </HierarchicalDataTemplate>

    <!-- data template for FolderItem instances -->
    <HierarchicalDataTemplate DataType="{x:Type vm:FolderItem}"
                              ItemsSource="{Binding Path=Items}">
      <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>

  </Window.Resources>

  <!-- the treeview control -->
  <TreeView x:Name="farmsTree" />

</Window> 

Of course, you can easily style any of the data templates to your liking. You can find the complete sample from the link at the top of this post. Enjoy! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect I'm a gun for hire
Switzerland Switzerland
Philipp is an independent software engineer with great love for all things .NET.
He lives in Winterthur, Switzerland and his home on the web is at http://www.hardcodet.net.

Comments and Discussions

 
QuestionHow to add a 3rd (or more) levels? Pin
Kevin Miller18-Jun-17 4:45
Kevin Miller18-Jun-17 4:45 
GeneralMy vote of 5 Pin
Kevin Miller18-Jun-17 4:27
Kevin Miller18-Jun-17 4:27 
QuestionGreat solution for real-world scenarios, but... Pin
PandaDad9-May-17 14:02
PandaDad9-May-17 14:02 
QuestionGreat Article! Pin
eduardolucioac24-Feb-12 4:45
eduardolucioac24-Feb-12 4:45 
Generalexactly what i need Pin
SeriousM18-Mar-10 21:42
SeriousM18-Mar-10 21:42 
GeneralVery cool! Question on updates [modified] Pin
Janene Mc1-Feb-10 6:11
Janene Mc1-Feb-10 6:11 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi1-Feb-10 6:43
Philipp Sumi1-Feb-10 6:43 
GeneralRe: Very cool! Question on updates [modified] Pin
Janene Mc1-Feb-10 6:52
Janene Mc1-Feb-10 6:52 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi1-Feb-10 7:19
Philipp Sumi1-Feb-10 7:19 
GeneralRe: Very cool! Question on updates Pin
Janene Mc1-Feb-10 7:25
Janene Mc1-Feb-10 7:25 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi1-Feb-10 7:30
Philipp Sumi1-Feb-10 7:30 
GeneralRe: Very cool! Question on updates Pin
Janene Mc1-Feb-10 7:34
Janene Mc1-Feb-10 7:34 
GeneralRe: Very cool! Question on updates Pin
Janene Mc1-Feb-10 8:04
Janene Mc1-Feb-10 8:04 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi1-Feb-10 9:04
Philipp Sumi1-Feb-10 9:04 
GeneralRe: Very cool! Question on updates Pin
Janene Mc1-Feb-10 9:08
Janene Mc1-Feb-10 9:08 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi4-Feb-10 5:24
Philipp Sumi4-Feb-10 5:24 
GeneralRe: Very cool! Question on updates Pin
Janene Mc4-Feb-10 5:40
Janene Mc4-Feb-10 5:40 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi7-Feb-10 13:17
Philipp Sumi7-Feb-10 13:17 
GeneralRe: Very cool! Question on updates Pin
Janene Mc9-Feb-10 9:45
Janene Mc9-Feb-10 9:45 
GeneralRe: Very cool! Question on updates Pin
Philipp Sumi14-Feb-10 11:40
Philipp Sumi14-Feb-10 11:40 
GeneralDefinitely Useful Pin
Lee Humphries15-May-09 11:45
professionalLee Humphries15-May-09 11:45 
GeneralRe: Definitely Useful Pin
Philipp Sumi15-May-09 12:39
Philipp Sumi15-May-09 12:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.