David Brunelle
David Brunelle

Reputation: 6450

Build a treeview in WPF

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?

Upvotes: 0

Views: 5156

Answers (3)

Thomas Levesque
Thomas Levesque

Reputation: 292645

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

Upvotes: 4

Tobias
Tobias

Reputation: 38344

Maybe a little late for your problem, but somebody who is running into same problem. I found a very good free Control for WPF: DW.WPFToolkit With a good documentation..

Upvotes: 0

Paul Williams
Paul Williams

Reputation: 617

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

Upvotes: 2

Related Questions