Search code examples
wpftreeview

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?


Solution

  • 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