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

app*_*eek 1 c# datatemplate xamarin xamarin.forms .net-standard

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

视图/页面的内容是绑定到TemplateItem对象列表的列表视图。每个列表视图项,TemplateItem,应该看起来一样(作为一篇文章)。但是,当该属性BlockTypeTemplateItemslideshow,列表视图必须考虑使用另一种数据模板不同。

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

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是模型类:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是一个线框,向您展示我正在尝试完成的任务:

我试图完成的线框

小智 5

尝试使用 DataTemplateSelector 而不是使用 DataTemplate。以便您可以为不同的对象设置不同的模板。 参考链接: https : //docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector

  • 鼓励链接到外部资源,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及它为什么在那里。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。 (3认同)