WPF TreeView template with different classes

后端 未结 2 1967
迷失自我
迷失自我 2021-01-28 11:13

How to write XAML for WPF TreeView so when I bind ViewModel with following structure?

public class A
{
    int Id { get; set; }
    string Name { get; set; }
             


        
2条回答
  •  忘掉有多难
    2021-01-28 12:06

    If you don't want to change the tree structure (class structure):

    
      
        
          
          
        
      
      
        
          
        
      
      
        
          
        
      
      
        
          
        
      
    
    

    The Style to adjust the appearance. It's the default TreeViewItem style taken from Microsoft Docs: TreeView Styles and Templates with a modified "Expander" positioning and removed border of the nested TreeView to maintain the default look. You can apply the Style (and its resources) locally by setting the TreeView.ItemContainerStyle property or by putting the Style into a ResourceDictionary within the scope of the target TreeView(e.g., App.xaml):

    
    
    
    #FF444444
    #FFC5CBF9
    #FFDDDDDD
    
    
    
    
    
    
    

    Recommended

    You should definitely change the class structure and introduce a common base type:

    interface IDevice
    {
      int Id { get; set; }
      List Items { get; set; }
    }
    
    class A : IDevice
    {
      public A()
      {
        this.Items = new List { new B(), new C() };
      }
    }
    
    class B : IDevice
    {}
    

    You can now add every type that implements IDevice to the child collection, even mixed. Simply add a HierachricalDataTemplate for each implementation of IDevice:

    
      
        
      
      
        
      
      
        
      
      
        
      
    
    

提交回复
热议问题