Hi guys,
what I would like to share with you today is how to display data in hierarchical view in WPF via the powerful mechanism of databinding! The source code is downloadable here as well as the Artists.xml file.
The below pictures displays an XML file and the relevant representation in a WPF TreeView.


The code for building an Hierarchical TreeView using WPF HierarchicalDataTemplate is copy-paste below:


            <!-- Data Binding to Artists.xml -->
            <XmlDataProvider x:Key="myArtistsData" Source="DataSources/Artists.xml" XPath="/Artists" />

            <!--Template for "Song" -->
            <HierarchicalDataTemplate x:Key="song_hdt">
                <TextBlock Text="{Binding XPath=@Name}" />

            <!-- Template for "Album" -->
            <HierarchicalDataTemplate x:Key="album_hdt"
                                      ItemTemplate="{StaticResource song_hdt}"
                                      ItemsSource="{Binding XPath=Songs/Song}">
                <TextBlock Text="{Binding XPath=@Name}" />

            <!-- Template for "Artist" -->
            <HierarchicalDataTemplate x:Key="artist_hdt"
                                      ItemTemplate="{StaticResource album_hdt}"
                                      ItemsSource="{Binding XPath=Albums/Album}">
                <TextBlock Text="{Binding XPath=@Name}" />


        <TreeView ItemsSource="{Binding Source={StaticResource myArtistsData}, XPath=Artist}"
                  ItemTemplate="{StaticResource artist_hdt}"/>


The XmlDataProvider is used as item source for the TreeView via binding. The TreeView specifies as ItemTemplate the artist_hdt which is a HierarchicalDataTemplate that is used in the following way:

  • Everything you put inside HierarchicalDataTemplate tag is used for displaying the current item
  • ItemsSource defines which data shall be displayed as child of current item
  • ItemTemplate defines the way to be used to display child data

Hope to be helpful 🙂