Xamarin.Forms 为列表视图中的特定项目显示不同的数据模板

Xamarin.Forms show a different datatemplate for a specific item in listview

我目前正在使用 Xamarin.Forms 和 .Net Standard 开发动态应用程序。 我正在使用 MVVM 作为代码模式。视图背后没有代码。

view/page 的内容是绑定到 TemplateItem 对象列表的列表视图。每个列表视图项目 TemplateItem 应该看起来一样(作为一篇文章)。但是当 TemplateItem 的 属性 BlockTypeslideshow 时,列表视图必须通过使用另一个数据模板看起来不同。

当对象的 属性 不同时,如何为列表视图项目使用另一个数据模板?

这是我的 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>

这是模型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; }
}

这是一个线框图,向您展示我正在努力完成的工作:

WireFrame of what I am trying to accomplish

尝试使用 DataTemplateSelector,而不是使用 DataTemplate。这样您就可以为不同的对象设置不同的模板。 Reference Link : https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector