Using HierarchicalDataTemplate to bind TreeView in WPF

Just sharing a simple example that shows how to bind the XML data to TreeView using HierarchicalDataTemplate.

Suppose this is our XML file named Packages.xml

This is the XAML used

<Window x:Class="SampleSyncServerAdminTool.MainWindow"
 Title="MainWindow" Height="350" Width="525">

 <XmlDataProvider x:Key="MyList" Source="Packages.xml" XPath="Packages"/>

<HierarchicalDataTemplate DataType="Packages" ItemsSource="{Binding XPath=*}">
 <TextBlock Text="Packages"></TextBlock>

<HierarchicalDataTemplate DataType="Package" ItemsSource="{Binding XPath=*}">
 <TextBlock Text="{Binding XPath=@Name}"></TextBlock>

<HierarchicalDataTemplate DataType="Batch" ItemsSource="{Binding XPath=*}">
 <TextBlock Text="{Binding XPath=@Name}"></TextBlock>

 <TreeView DockPanel.Dock="Left" Width="150" Name="treeViewPackages"
 ItemsSource="{Binding Source={StaticResource MyList}}">
 <Grid DockPanel.Dock="Right">

The TreeView showing package information.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s