Skip to content

Instantly share code, notes, and snippets.

@JoeRobich
Created June 30, 2016 14:21
Show Gist options
  • Save JoeRobich/735060487c30df126f081a37c95c4a42 to your computer and use it in GitHub Desktop.
Save JoeRobich/735060487c30df126f081a37c95c4a42 to your computer and use it in GitHub Desktop.
XAML DataTemplateSelector Example
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace DataTemplates
{
public class ThingTemplateSelector : DataTemplateSelector
{
private readonly Dictionary<Type, Func<DataTemplate>> TemplatesByType;
public DataTemplate RedThingTemplate { get; set; }
public DataTemplate BlueThingTemplate { get; set; }
public ThingTemplateSelector()
{
TemplatesByType = new Dictionary<Type, Func<DataTemplate>>
{
{ typeof(RedThing), () => RedThingTemplate },
{ typeof(BlueThing), () => BlueThingTemplate }
};
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
DataTemplate dataTemplate;
if (TemplatesByType.TryGetValue(item?.GetType(), out dataTemplate))
return dataTemplate;
return base.SelectTemplateCore(item, container);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment