How to mix databound and static levels in a TreeView?

后端 未结 4 1622
感动是毒
感动是毒 2021-02-03 10:23

I have a collection of Database objects, each containing collections of Schema objects and User objects. I want to bind them to a TreeView, but adding

4条回答
  •  爱一瞬间的悲伤
    2021-02-03 10:46

    The problem is that a TreeView is not very well suited to what you want to acomplish: It expects all the subnodes to be of the same type. As your database node has a node of type Collection> and of type Collection> you cannot use a HierarchicalDataTemplate. A Better approach is to use nested expanders that contain ListBoxes.

    The code below does what you want I think,while being as close as possible to your original intent:

    
        
            
            
                    
                        
                            
                        
                        
                        
                    
                     
            
            
                
            
            
                
            
        
        
            
            
        
    
    
    using System.Collections.ObjectModel;
    using System.Windows;
    
    namespace TreeViewSelection
    {
        public partial class Window1 : Window
        {
            public ObservableCollection DataBases { get; set; }
            public Window1()
            {
                InitializeComponent();
                DataBases = new ObservableCollection
                                {
                                    new Database("Db1"),
                                    new Database("Db2")
                                };
                DataContext = this;
            }
        }
    
        public class Database:DependencyObject
        {
            public string Name { get; set; }
            public ObservableCollection Schemas { get; set; }
            public ObservableCollection Users { get; set; }
    
            public Database(string name)
            {
                Name = name;
                Schemas=new ObservableCollection
                            {
                                new Schema("Schema1"),
                                new Schema("Schema2")
                            };
                Users=new ObservableCollection
                          {
                              new User("User1"),
                              new User("User2")
                          };
            }
        }
    
        public class Schema:DependencyObject
        {
            public string Name { get; set; }
            public Schema(string name)
            {
                Name = name;   
            }
        }
    
        public class User:DependencyObject
        {
            public string Name { get; set; }
            public User(string name)
            {
                Name = name;
            }
        }
    }
    

提交回复
热议问题