ItemsControl with multiple DataTemplates for a viewmodel

前端 未结 4 1496
陌清茗
陌清茗 2020-11-29 04:59

is it possible to bind an itemscontrol with canvas as template to multiple DataTemplates?

I have 2 collections and depending on the type I would like to display a di

4条回答
  •  庸人自扰
    2020-11-29 05:14

    You can create multiple ObservableCollections and then bind your ItemsSource to a CompositeCollection which joins those collections.

    Then in your XAML you can create different DataTemplates for the respective types using the DataType property which like styles gets automatically applied if it is placed in the resources. (You can also create the composite in XAML which is shown on MSDN, if the CollectionContainers should be bound that is a bit more difficult though)

    Example code:

    ObservableCollection data1 = new ObservableCollection(new Employee[]
    {
        new Employee("Hans", "Programmer"),
        new Employee("Elister", "Programmer"),
        new Employee("Steve", "GUI Designer"),
        new Employee("Stefan", "GUI Designer"),
        new Employee("Joe", "Coffee Getter"),
        new Employee("Julien", "Programmer"),
    });
    ObservableCollection data2 = new ObservableCollection(new Machine[]
    {
        new Machine("E12", "GreedCorp"),
        new Machine("E11", "GreedCorp"),
        new Machine("F1-MII", "CommerceComp"),
        new Machine("F2-E5", "CommerceComp")
    });
    CompositeCollection coll = new CompositeCollection();
    coll.Add(new CollectionContainer() { Collection = data1 });
    coll.Add(new CollectionContainer() { Collection = data2 });
    Data = coll;
    
    
        
            
                
            
        
        
            
                
                    
                    
                    
                    
                
            
            
                
                    
                    
                    
                
            
        
    
    

    Here i use a different panel but it should be the same for a canvas.

提交回复
热议问题