Created
June 30, 2016 14:21
-
-
Save JoeRobich/735060487c30df126f081a37c95c4a42 to your computer and use it in GitHub Desktop.
XAML DataTemplateSelector Example
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 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