WPF TreeView HierarchicalDataTemplate - binding to object with different child collections

前端 未结 3 849
你的背包
你的背包 2021-01-14 13:33

I am trying to bind a collection to wpf TreeView control using data templates. Each item(Person) in the collection also contains two different collections(Cars,

3条回答
  •  死守一世寂寞
    2021-01-14 14:14

    It is a bit complicated since your tree has two different child collections. WPF does not support a scenario with multiple ItemsSource definitions. Therefore you need to combine those collection into a CompositeCollection. The type matching of the composite elements (i.e. Car, Book) will be done automatically.

    In XAML you need to define so-called HierarchicalDataTemplates that match your type definitions. If local points to the namepace where Book, Car and Person are defined, the simplified HierarchicalDataTemplates could look like this:

     
            
        
    
        
            
            
        
    
        
            
            
        
    

    Then you need to hook up your collection to the tree control. There are a few possibilities to do this, the easiest would be to define a property in your Window class and define a Binding:

    
    

    This should point you into the right direction, but don't take my code as compile ready :-)

提交回复
热议问题