views:

86

answers:

1

Lets say I have the following data:

<XmlDataProvider x:Key="Values">
  <x:XData>
    <folder name="C:">
      <folder name="stuff" />
      <folder name="things" />
      <folder name="windows">
        <folder name="system32" />
      </folder>
    </folder>
  </x:XData>
</XmlDataProvider>

How can I get that into a treeview? I can't seem to grok hierarchical binding...

I know that I can get it in there in C# code, but I wanted to do it with a binding expression.

+4  A: 

EDIT: Didn't see that you wanted to do this in XAML only. This MSDN post should help you out.

HierarchicalDataTemplate isn't so bad if your data is already in a hierarchical form. Let's say you translate that XML data into a model class using code like this:

public partial class TreeViewHierarchy : Window
{
    public ObservableCollection<Folder> Folders
    {
        get;
        set;
    }

    public TreeViewHierarchy()
    {
        Folder system32 = new Folder() { Name = "system32" };
        Folder windows = new Folder() { Name = "windows", 
            Children = new ObservableCollection<Folder>() { system32 } };

        Folder things = new Folder() { Name = "things" };
        Folder stuff = new Folder() { Name = "stuff" };

        Folder c = new Folder() { Name = "C:",
            Children = new ObservableCollection<Folder>() { stuff, things, windows } };

        Folders = new ObservableCollection<Folder>() { c };

        InitializeComponent();

    }
}

public class Folder
{
    public string Name
    {
        get;
        set;
    }

    public ObservableCollection<Folder> Children
    {
        get;
        set;
    }
}

Then the XAML for your TreeView would be as simple as this:

<Window x:Class="TestWpfApplication.TreeViewHierarchy"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TreeViewHierarchy" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TreeView ItemsSource="{Binding Folders}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

And the result:

alt text

Charlie
+1 It's worth highlighting the important part of the xaml is where you bind the 'ItemsSource' of the HierarchicalDataTemplate to the 'Children' collection of the Folder object... Great answer :)
IanR
Perfect, thanks.
John Gietzen