WPF: Correctly storing an object in a TreeViewItem

后端 未结 2 1576
遇见更好的自我
遇见更好的自我 2021-01-03 04:13

To store an object (say, an instance of a class) in a TreeViewItem, I am currently storing the object in the TreeViewItem\'s Header and then overri

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 04:37

    The "proper" way is to just add the object to the TreeView's (or TreeViewItem's) Items collection and use a HierarchicalDataTemplate to control how the item is rendered:

    Person.cs:

    public class Person
    {
        private readonly ICollection _children = new ObservableCollection();
    
        public string Name { get; set; }
    
        public ICollection Children
        {
            get
            {
                return _children;
            }
        }
    }
    

    Window1.xaml.cs:

    public Window1()
    {
        InitializeComponent();
    
        var people = new List();
        var kent = new Person() { Name = "Kent" };
        kent.Children.Add(new Person() { Name = "Tempany" });
        people.Add(kent);
        _treeView.ItemsSource = people;
    }
    

    Window1.xaml:

    
        
            
                
            
        
    
    

提交回复
热议问题