Build a treeview in WPF

前端 未结 3 1137
渐次进展
渐次进展 2020-12-22 06:27

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 them

相关标签:
3条回答
  • 2020-12-22 06:57

    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

    0 讨论(0)
  • 2020-12-22 06:59

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

    0 讨论(0)
  • 2020-12-22 07:22

    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..

    0 讨论(0)
提交回复
热议问题