我是Xamarin的新手。我有一个要求,我必须实现一个ListView或说tableView有多个不同的类型大小的单元格。 而且我还必须为特定的单元格部分添加Header,并且我的一些自定义单元格中有一个水平滚动。
我之前在iOS原生UITableView中做过这件事,但不知道Xamarin跨平台是如何完成的,有谁可以帮我解决这个问题?
答案 0 :(得分:10)
您正在寻找DataTemplateSelector
,这在官方Xamarin.Forms documentation中有详细记录。
基础是您创建自己的DataTemplateSelector
类:
public class MyDataTemplateSelector : DataTemplateSelector
{
}
在该课程中,您会覆盖OnSelectTemplate
:
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
}
通过检查item
参数的类型,您应该能够找出要返回的模板。
因此,假设ViewModel
为Dog
,Cat
为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;
}
}
显示不同的<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
然后你可以在你的XAML中使用它:
dogCatTemplateSelector
然后,只需将ListView
设置为您在<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
看起来像是:
isIPFS
然后你只用狗和猫的实例填充 function ref_and_close()
{
opener.location.reload();
self.close();
}
//just call the function
ref_and_close();
。