tags:

views:

229

answers:

2

I am trying to build a three level treeview in WPF. Basically, I have a list of top level items that all have one more child items. Those child item may or may not have themselves chid items.

Anyone know of a tutorial available on the net?

+1  A: 

This example may be what you need: http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx

Paul Williams
Wow... didn't know it could be so complicated for something so simple...
David Brunelle
+2  A: 

The simplest way is to use bindings and HierarchicalDataTemplate. Declare a class with your data :

class Item : INotifyPropertyChanged
{
    public Item()
    {
        this.Children = new ObservableCollection<Item>();
    }

    public event PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public ObservableCollection<Item> Children { get; private set; }
}

And define a HierarchicalDataTemplate for this type :

<HierarchicalDataTemplate DataType="{x:Type my:Item}"
                          ItemsSource="{Binding Items}">
    <TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>

Now you just need to bind the ItemsSource of the TreeView to your collection of top-level items, and the tree nodes will be constructed automatically. If you need to add (or remove) a node, just add an item to (or remove it from) the parent collection

For this example, I used a single item type, but if you have several types to display in the TreeView you will need to define a HierarchicalDataTemplate for each. For leaf nodes (nodes with no children), you can just use a regular DataTemplate

Thomas Levesque
If you omit the fact that I don't declare the DataType and that Header doesn't seem to exist, I was able to make it work with different objects with more then one type. the displayed date have the same property name so it worked.It might not be the best way, but since the display has to be simple, I will do it like this for now.
David Brunelle
Indeed there was an error in my code, the Header property doesn't exist... it's fixed now
Thomas Levesque