我是 Xamarin 的新手。我有一个要求,我必须实现一个 ListView 或说具有多个不同类型大小单元格的 tableView。 而且我还必须为单元格的特定部分添加标题,并且我的一些自定义单元格中有一个水平滚动条。
我以前在 iOS 原生 UITableView 中做过这件事,但不知道在 Xamarin 跨平台中是怎么做到的,谁能帮我解决这个问题?
最佳答案
您正在寻找 DataTemplateSelector
,它在官方 Xamarin.Forms documentation 中有很好的记录.
基础知识是您创建自己的 DataTemplateSelector
类:
public class MyDataTemplateSelector : DataTemplateSelector
{
}
在该类中,您重写 OnSelectTemplate
:
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
}
通过检查 item
参数的类型,您应该能够确定返回哪个模板。
假设您有一个用于 Dog
的 ViewModel
和一个用于 Cat
的 ViewModel
并且想要显示不同的 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/