XML to TreeView HierarchicalDataTemplate in Silverlight3 toolkit

28 02 2010


<?xml version="1.0" encoding="utf-8"?>
  <Folder Name="1">
    <Folder Name="1.1">
      <Folder Name="1.1.1">
        <Folder Name="">
          <File Name="file1"></File>
        </Folder >
      </Folder >
    </Folder >
  <Folder Name="f2">
    <Folder Name="f2">
      <File Name="file21"></File>
      <File Name="file22"></File>
  <Folder Name="f">
    <File Name="file31"></File>
    <File Name="file32"></File>

First define your data structure.

Load the the structure from XML. You need recursion to load the folders.

In the Silverlight application:

1. Use Silverlight Toolkit TreeView control

2. Define HierarchicalDataTemplate

3. Set the item source

Check the sample below :

    <Grid x:Name="LayoutRoot"
            <common:HierarchicalDataTemplate x:Key="NodeTemplate"
                                             ItemsSource="{Binding Folders}">
                <Grid Width="Auto">
                        <RowDefinition />
                        <RowDefinition />
                    <TextBlock Text="{Binding Name}">
                    <ListBox Grid.Row="1"
                             ItemsSource="{Binding FileNames}"></ListBox>

        <controls:TreeView x:Name="tvFolders"
                           ItemTemplate="{StaticResource NodeTemplate}">

    public partial class TreeViewSample : UserControl
        public TreeViewSample()

            tvFolders.ItemsSource = this.LoadFromXML();


        public List<Folder> LoadFromXML()
            XElement elementLoaded = XElement.Load("XMLFile1.xml");
            List<Folder> folders = new List<Folder>();
            this.LoadFolders(elementLoaded.Elements("Folder").ToList(), folders);

            return folders;

        public void LoadFolders(List<XElement> elmFolders, List<Folder> folders)
            foreach (var item in elmFolders)
                var folder = new Folder
                    Name = item.Attribute("Name").Value,
                    Folders = new List<Folder>(),
                    FileNames = item.Elements("File").Select(s => s.Attribute("Name").Value).ToList()
                this.LoadFolders(item.Elements("Folder").ToList(), folder.Folders);

    public class Folder
        public string Name { get; set; }
        public List<Folder> Folders { get; set; }
        public List<string> FileNames { get; set; }