Xamarin.Forms为listview中的特定项显示不同的datatemplate

时间:2018-03-18 14:13:53

标签: c# xamarin xamarin.forms datatemplate .net-standard

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

视图/页面的内容是绑定到TemplateItem个对象列表的列表视图。每个列表视图项TemplateItem应该看起来都一样(作为文章)。但是,当BlockType的属性TemplateItemslideshow时,列表视图必须使用其他数据模板才能看起来不同。

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

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

这是模型类:

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

1 个答案:

答案 0 :(得分:2)

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