Reputation: 1110
I am working on a Xamarin.Forms project. It has multiple pages with ListViews that display content that requires templates. How can I easily reuse one template thought the whole project because right now I have to update the templates on each page everytime I change something in one.
I have created a template as such in each page's xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:*snip*.Renderers;assembly=*snip*"
x:Class="*snip*.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="template1">
<local:PostViewCell>
<StackLayout BackgroundColor="White" Margin="10, 10, 10, 10" Padding="10, 10, 10, 10">
. . .
</StackLayout>
</local:PostViewCell>
</DataTemplate>
<DataTemplate x:Key="template2">
<local:PostViewCell>
<StackLayout BackgroundColor="White" Margin="10, 10, 10, 10" Padding="10, 10, 10, 10">
. . .
</StackLayout>
</local:PostViewCell>
</DataTemplate>
<local:PostTemplateSelector x:Key="templateSelector"
Template1="{StaticResource template1}"
Template2="{StaticResource template2}" ></local:PostTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<local:PostListView x:Name="PostListView" ItemTemplate="{StaticResource templateSelector}"/>
</StackLayout>
</ContentPage.Content>
Upvotes: 2
Views: 1031
Reputation: 419
Define your Datatemplate with Unique key in App.Xaml Like,
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourAppName.App">
<Application.Resources>
<ResourceDictionary>
<DataTemplate x:Key="lstTemplate">
<ViewCell>
<------Your Design here------->
</ViewCell>
</DataTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
Use that lstTemplate key in your Listview Like,
<ListView x:Name=lst"
ItemsSource="{Binding Name}"
SeparatorColor="#0094FF" ItemTemplate="{StaticResource lstTemplate}">
Upvotes: 4
Reputation: 89082
You can define the DataTemplate
as a resource in App.xaml
and refer to it from individual XAML pages
Upvotes: 2