Using HierarchicalDataTemplate to bind TreeView in WPF
Views (119)
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.
Filed under: WPF Tagged: WPF
This was originally posted here.

Like
Report
*This post is locked for comments