xaml - Xamarin 表单(跨平台): Multiple type of cells in ListView

标签 xaml listview xamarin xamarin.forms cross-platform

我是 Xamarin 的新手。我有一个要求,我必须实现一个 ListView 或说具有多个不同类型大小单元格的 tableView。 而且我还必须为单元格的特定部分添加标题,并且我的一些自定义单元格中有一个水平滚动条。 Here I attached the image for my listview requirement.

我以前在 iOS 原生 UITableView 中做过这件事,但不知道在 Xamarin 跨平台中是怎么做到的,谁能帮我解决这个问题?

最佳答案

您正在寻找 DataTemplateSelector,它在官方 Xamarin.Forms documentation 中有很好的记录.

基础知识是您创建自己的 DataTemplateSelector 类:

public class MyDataTemplateSelector : DataTemplateSelector
{

}

在该类中,您重写 OnSelectTemplate:

protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
}

通过检查 item 参数的类型,您应该能够确定返回哪个模板。

假设您有一个用于 DogViewModel 和一个用于 CatViewModel 并且想要显示不同的 DataTemplate 对于每一个。你会做这样的事情:

public class DogCatTemplateSelector : DataTemplateSelector
{
    public DataTemplate DogTemplate { get; set; }
    public DataTemplate CatTemplate { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if (item is DogViewModel)
            return DogTemplate;
        return CatTemplate;
    }
}

然后您可以在 XAML 中使用它:

<ContentPage.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="dogTemplate">
            <ViewCell>
                ... <---- define your look of dog template here
            </ViewCell>
        </DataTemplate>
        <DataTemplate x:Key="catTemplate">
            <ViewCell>
                ... <---- define your look of cat template here
            </ViewCell>
        </DataTemplate>
        <local:DogCatTemplateSelector x:Key="dogCatTemplateSelector"
            DogTemplate="{StaticResource dogTemplate}"
            CatTemplate="{StaticResource catTemplate}" />
    </ResourceDictionary>
</ContentPage.Resources>

然后只需将 ItemTemplate 设置为您在 ListView 的资源中定义的 dogCatTemplateSelector 实例:

<ListView ItemsSource="{Binding DogsCatsCollection}" ItemTemplate="{StaticResource dogCatTemplateSelector}" />

你的 ViewModel 看起来像这样:

public class Animal : INotifyPropertyChanged
{
}

public class DogViewModel : Animal
{
}

public class CatViewModel : Animal
{
}

public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Animal> DogsCatsCollection { get; }
        = new ObservableCollection<Animal>();
}

然后您只需使用狗和猫的实例填充 DogsCatsCollection

关于xaml - Xamarin 表单(跨平台): Multiple type of cells in ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832940/

相关文章:

Android ListView 不同的分割线图片

c# - 如何在触摸屏中滚动 ListView

c# - 如何使用 xamarin android 访问 WCF 服务器

xaml - 访问文本 block 的背景色

c# - Xamarin Xaml 和多目标

android - 更新 SimpleCursorAdapter,同时保持 ListView 中的滚动位置

android - HttpClient-Xamarin 安卓-MvvmCross

c# - Xamarin 使用 FontAwesome 创建自定义按钮

html - 即使控件是从 HTML/JS 或 XAML 创建的,Metro 控件是否会在低级别重用相同的代码路径?

wpf - 在右键单击MVVM的treeView中选择节点