我需要在 Xamarin 表单中制作一个 CarouselView,其中每张幻灯片都有一个特定的模板。 目前我已经这样做了:
XAML:
xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
.......
<ContentView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<control:CarouselView x:Name="carouselView">
<control:CarouselView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Testo}" />
</DataTemplate>
</control:CarouselView.ItemTemplate>
</control:CarouselView>
</ContentView>
代码隐藏:
List<CustomCell> myCarousel = new List<CustomCell>();
myCarousel.Add(new CustomCell { Testo = "ciao" });
myCarousel.Add(new CustomCell { Testo = "ciao due" });
carouselView.ItemsSource = myCarousel;
自定义单元格:
public class CustomCell
{
public string Testo { get; set; }
}
所有这一切都有效,我的问题是每张幻灯片都有不同的模板,例如,每张幻灯片的图形不同的网格,这是因为我必须以不同的图形方式显示数据。 你能推荐一个解决方案吗?谢谢
最佳答案
您可以使用 data template selector自定义 CarouselView 中不同项目的外观。一个简单的例子:
MyDataTemplateSelector.cs
public class MyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate SimpleTemplate { get; set; }
public DataTemplate ComplexTemplate { get; set; }
public MyDataTemplateSelector()
{
SimpleTemplate = new DataTemplate(typeof(SimpleView));
ComplexTemplate = new DataTemplate(typeof(ComplexView));
}
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
CustomCell cell = (CustomCell)item;
if (cell.Testo.Length > 5) {
return ComplexTemplate;
} else {
return SimpleTemplate;
}
}
}
简单 View .xaml
<ContentView>
<StackLayout BackgroundColor="Red">
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentView>
复杂 View .xaml
<ContentView>
<StackLayout BackgroundColor="Yellow" >
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" />
<Label Text="I lied about this being complex" />
</StackLayout>
</ContentView>
并且在您的 CarouselView 所在的页面中:
<ContentPage.Resources>
<ResourceDictionary>
<local:MyDataTemplateSelector x:Key="templateSelector"></local:MyDataTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
....
<control:CarouselView x:Name="carouselView" ItemTemplate="{StaticResource templateSelector}" />
关于c# - Xamarin 表单中每张幻灯片使用不同模板的 CarouselView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672353/