UWP DataTemplates for multiple item types in ListView

后端 未结 2 1786
梦如初夏
梦如初夏 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:31

    The clue is in the error message.

    Failed to create a 'Ui.Components.TemplateMatch' from the text 'model:Dog'

    Note the 'model:Dog' is coming to your selector as text not a type.

    Change your TemplateMatch class TargetType property to string instead of type like this:-

    public class TemplateMatch
    {
        public string TargetType { get; set; }
        public DataTemplate Template { get; set; }
    }
    

    Then change your template selector class to read

    public class MyDataTemplateSelector : DataTemplateSelector
    {
        public ObservableCollection Matches { get; set; }
    
        public MyDataTemplateSelector()
        {
            Matches = new ObservableCollection();
        }
    
        protected override DataTemplate SelectTemplateCore(object item)
        {
            return Matches.FirstOrDefault(m => m.TargetType.Equals(item.GetType().ToString()))?.Template;
        }
    
        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            return Matches.FirstOrDefault(m => m.TargetType.Equals(item.GetType().ToString()))?.Template;
        }
    }
    

    Finally change your xaml to read

    
        
            
                
                    
                    
                
            
        
    
    

    The point is to forget trying to pass it to your selector as a type, and pass the typename as a string instead (Full namespace not Xaml namespace).

提交回复
热议问题