This repository was archived by the owner on Aug 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
NamedDataTemplateSelector
Mark Smith edited this page Aug 29, 2016
·
1 revision
The NamedDataTemplateSelector is a Xamarin.Forms DataTemplateSelector that looks up a DataTemplate dynamically based on the typename of the supplied BindingContext for the visual. It allows you to supply a heterogeneous collection of data to a ListView and get a unique data template for each unique System.Type.
-
StripNamespace: true to remove the namespace from the type name before resolving the resource.
In our VM or codebehind, we have a shape collection composed of different Shape-derived objects:
Shapes = new List<Shape> { new Circle(), new Square(), new Triangle() ... };Then in XAML, we data bind a ListView to this collection and set the ItemTemplate to be a NamedDataTemplateSelector. It will walk the resource tree (starting at the ListView) and identify each DataTemplate by the type name of the object being visualized (Circle, Square, Triangle).
<Page>
<Page.Resources>
<Page.ResourceDictionary>
<inf:NamedDataTemplateSelector x:Key="dtSelector" StripNamespace="true" />
</Page.ResourceDictionary>
<DataTemplate x:Key="Square">
...
</DataTemplate>
<DataTemplate x:Key="Circle">
...
</DataTemplate>
<DataTemplate x:Key="Triangle">
...
</DataTemplate>
</Page.Resources>
<ListView ItemsSource="{Binding Shapes}"
ItemTemplate="{StaticResource dtSelector}" .. />