How to mix databound and static levels in a TreeView?

后端 未结 4 1573
感动是毒
感动是毒 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:59

    Oh man this is an incredibly frustrating task. I've tried doing it myself many times. I had a very similar requirement where I've got something like a Customer class that has both a Locations collection and a Orders collection. I wanted Locations and Orders to be "folders" in the tree view. As you've discovered, all the TreeView examples that show you how to bind to self-referencing types are pretty much useless.

    First I resorted to manually building a tree of FolderItemNode and ItemNode objects that I would generate in the ViewModel but this defeated the purpose of binding because it would not respond to underlying collection changes.

    Then I came up with an approach which seems to work pretty well.

    • In the above described object model, I created classes LocationCollection and OrderCollection. They both inherit from ObservableCollection and override ToString() to return "Locations" and "Orders" respectively.
    • I create a MultiCollectionConverter class that implements IMultiValueConverter
    • I created a FolderNode class that has a Name and Items property. This is the placeholder object that will represent your "folders" in the tree view.
    • Define hierarchicaldatatemplate's that use MultiBinding anywhere that you want to group multiple child collections into folders.

    The resulting XAML looks similar to the code below and you can grab a zip file which has all the classes and XAML in a working example.

    
    
        
    
            
            
                
    
            
            
                
                    
                        
                            
                        
                        
                        
                    
                
                
    
            
            
                
            
                
    
        
    
        
            
            
        
    
    
    

    Folders in TreeView

提交回复
热议问题