How would I go about implementing this?
Let\'s say this is my model:
public interface IAnimal
{
string Name { get; }
}
public class Fish : IAnimal
{
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).