Created
May 10, 2017 22:36
-
-
Save weitzhandler/518611472d5081bdcbce6a066238b55d to your computer and use it in GitHub Desktop.
Xamarin DataTemplateSelector TargetType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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