[英]CarouselView with a different template for each slide in Xamarin forms
I need to make a CarouselView in Xamarin forms where every slide has a specific template. 我需要以Xamarin形式制作CarouselView,其中每个幻灯片都有一个特定的模板。 Currently I have done so:
目前,我已经这样做了:
XAML : 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>
CODEBEHIND : CODEBEHIND :
List<CustomCell> myCarousel = new List<CustomCell>();
myCarousel.Add(new CustomCell { Testo = "ciao" });
myCarousel.Add(new CustomCell { Testo = "ciao due" });
carouselView.ItemsSource = myCarousel;
CustomCell : CustomCell :
public class CustomCell
{
public string Testo { get; set; }
}
All this works, my problem is that I'd have a different template for each slide, for example, a grid different graphically each slide, this is because I have to display data differently graphically speaking. 所有这些工作正常,我的问题是每个幻灯片都有一个不同的模板,例如,每个幻灯片在图形上都不同的网格,这是因为我必须以图形方式显示不同的数据。 Can you recommend a solution?
您能推荐一个解决方案吗? Thank you
谢谢
You can use a data template selector to customize the look of different items in the CarouselView. 您可以使用数据模板选择器来自定义CarouselView中不同项目的外观。 A simple example:
一个简单的例子:
MyDataTemplateSelector.cs 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;
}
}
}
SimpleView.xaml SimpleView.xaml
<ContentView>
<StackLayout BackgroundColor="Red">
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentView>
ComplexView.xaml ComplexView.xaml
<ContentView>
<StackLayout BackgroundColor="Yellow" >
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" />
<Label Text="I lied about this being complex" />
</StackLayout>
</ContentView>
And in the page where your CarouselView is: 在CarouselView所在的页面中:
<ContentPage.Resources>
<ResourceDictionary>
<local:MyDataTemplateSelector x:Key="templateSelector"></local:MyDataTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
....
<control:CarouselView x:Name="carouselView" ItemTemplate="{StaticResource templateSelector}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.