Skip to content

Instantly share code, notes, and snippets.

@weitzhandler
Created May 10, 2017 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weitzhandler/518611472d5081bdcbce6a066238b55d to your computer and use it in GitHub Desktop.
Save weitzhandler/518611472d5081bdcbce6a066238b55d to your computer and use it in GitHub Desktop.
Xamarin DataTemplateSelector TargetType
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
namespace Xamarin.Forms
{
[ContentProperty(nameof(Templates))]
public class MultiDataTemplateSelector : DataTemplateSelector
{
public IList<TypedDataTemplate> Templates { get; } = new ObservableCollection<TypedDataTemplate>();
public MultiDataTemplateSelector()
{
var incc = (INotifyCollectionChanged)Templates;
incc.CollectionChanged += (sender, e) =>
{
if (e?.NewItems.Cast<TypedDataTemplate>()
.Any(tdt => tdt?.TargetType == null || tdt?.Template == null) == true)
throw new InvalidOperationException("All items must have all properties set.");
};
}
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
if (item == null) return null;
if (!Templates.Any()) throw new InvalidOperationException("No DataTemplates found.");
var result =
Templates.FirstOrDefault(t => t.TargetType.GetTypeInfo().IsAssignableFrom(item.GetType().GetTypeInfo()));
if (result == null)
throw new ArgumentOutOfRangeException($"Could not find a matching template for type '{item.GetType()}'.");
return result.Template;
}
}
[ContentProperty(nameof(Template))]
public class TypedDataTemplate
{
public Type TargetType { get; set; }
public DataTemplate Template { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment