05. DataTemplate

参考JusterZhu视频和文档,ppt文档基本全抄

一、DataTemplate

在日常开发中,会遇到需要在一个集合控件中通过某个Type属性选择不同的View显示在控件上。那么用常规的绑定是无法完成的,这时候微软提供了一个DataTemplateSelector对象帮助开发者完成此项功能。

实现步骤:
1.实现需要绑定的集合,并指定好类型
2.实现不同的DataTemplate,并实现好里面的样式
3.基于DataTemplateSelector实现自定义模板选择器
4.将DataTemplateSelector 、 DataTemplate、List、目标控件关联(绑定)起来。


    
        
    

    
        
            
                
                    
                    
                
            
        
        
            
                
                    
                    
                        
                    
                
            
        
        
            
                
                    
                    
                
            
        
        
            
                
                    
                    
                
            
        
        
    

    
        
    

internal class DataTypeTemplateSelector: DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is MainModel)
        {
            var model = item as MainModel;
            switch (model.Person) 
            {
                case Person.One:
                    return (container as FrameworkElement).FindResource("OneDataTemplate") as DataTemplate;
                case Person.Two:
                    return (container as FrameworkElement).FindResource("TwoDataTemplate") as DataTemplate;
                case Person.Three:
                    return (container as FrameworkElement).FindResource("ThreeDataTemplate") as DataTemplate;
                case Person.Four:
                    return (container as FrameworkElement).FindResource("FourDataTemplate") as DataTemplate;
            }
        }

        return base.SelectTemplate(item, container);
    }
}
public enum Person
{
    One, 
    Two, 
    Three, 
    Four 
}

internal class MainModel
{
    public string Name {  get; set; }
    public Person Person { get; set; }
    public string Color {  get; set; } 
}
internal class MainViewModel
{
    public ObservableCollection mainModels { get; set; }
    public MainViewModel()
    {
        mainModels = new ObservableCollection
        {
            new MainModel { Person = Person.One, Name = "dawa", Color = "Red" },
            new MainModel { Person = Person.Two, Name = "erwa", Color = "Green" },
            new MainModel { Person = Person.Three, Name = "sanwa", Color = "Blue" },
            new MainModel { Person = Person.Four, Name = "siwa", Color = "Yellow" }
        };
    }
}

你可能感兴趣的:(WPF,wpf)