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.

Artists.xml

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

    <Grid>
        <Grid.Resources>

            <!-- 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}" />
            </HierarchicalDataTemplate>

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

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

        </Grid.Resources>

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

    </Grid>

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 🙂
Cheers!

Advertisements