UWP DataTemplates for multiple item types in ListView

后端 未结 2 1792
梦如初夏
梦如初夏 2021-02-15 16:04

How would I go about implementing this?

Let\'s say this is my model:

public interface IAnimal
{
     string Name { get; }
}
public class Fish : IAnimal
{         


        
2条回答
  •  不思量自难忘°
    2021-02-15 16:42

    I found workaround. If you able to create instances of these types - you can use it for detecting types:

    [ContentProperty(Name = nameof(Matches))]
    public class TypeTemplateSelector : DataTemplateSelector
    {
        public ObservableCollection Matches { get; set; }
        public TypeTemplateSelector()
        {
            this.Matches = new ObservableCollection();
        }
    
        protected override DataTemplate SelectTemplateCore(object item)
        {
            return this.Matches.FirstOrDefault(m => m.ItemOfType.GetType().Equals(item.GetType()))?.TemplateContent;
        }
    
        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            return this.Matches.FirstOrDefault(m => m.ItemOfType.GetType().Equals(item.GetType()))?.TemplateContent;
        }
    }
    
    [ContentProperty(Name = nameof(ItemOfType))]
    public class TemplateMatch
    {
        public object ItemOfType { get; set; }
        public DataTemplate TemplateContent { get; set; }
    }
    

    XAML:

    
        
            
        
        
            
        
    
    

提交回复
热议问题