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"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="MainWindow" Height="350" Width="525">
 <Window.Resources>

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

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

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

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

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

The TreeView showing package information.

Bye.


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:

WordPress.com Logo

You are commenting using your WordPress.com 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