I'm currently developing a dynamic app using Xamarin.Forms with .Net Standard. I am using MVVM as code pattern. No code behind the view.
The content of the view/page is a listview bound to a list of TemplateItem
objects. Every listview item, TemplateItem
, should look the same (as an article). But when the property BlockType
of the TemplateItem
is slideshow
, the listview must look different by using another data template.
How can I use another data template for a listview item when a property of the object is different?
Here is my xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage"
NavigationPage.HasBackButton="True"
NavigationPage.HasNavigationBar="True"
Title="Overview">
<StackLayout >
<ActivityIndicator IsRunning="{Binding IsBusy}"
HorizontalOptions="CenterAndExpand" IsVisible="{Binding IsBusy}"/>
<ScrollView>
<StackLayout>
<ListView ItemsSource="{Binding LstTemplateList}" SeparatorVisibility="Default" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate x:Name="DTArticle">
<ViewCell>
<StackLayout>
<Label Text="{Binding Title}" FontSize="Large" />
<TextCell Text="ArticleDescription"/>
</StackLayout>
</ViewCell>
</DataTemplate>
<DataTemplate x:Name="DTSlideShow">
<ViewCell>
<!-- another DT for a slideshow -->
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ScrollView>
</StackLayout>
</ContentPage>
Here is the model class:
public class TemplateItem
{
public int Id { get; set; }
public String BlockType { get; set; }
public String Title { get; set; }
public String ArticleDescription { get; set; }
public List<String> LstImagePathsForSlideshow { get; set; }
}
Here is a wireframe to show you what I am trying to accomplish:
Instead of using DataTemplate, try to use DataTemplateSelector. So that you can set different template for different objects. Reference Link : https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector