I need to make a CarouselView in Xamarin forms where every slide has a specific template. Currently I have done so:
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 :
List<CustomCell> myCarousel = new List<CustomCell>();
myCarousel.Add(new CustomCell { Testo = "ciao" });
myCarousel.Add(new CustomCell { Testo = "ciao due" });
carouselView.ItemsSource = myCarousel;
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. A simple example:
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
<ContentView>
<StackLayout BackgroundColor="Red">
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentView>
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:
<ContentPage.Resources>
<ResourceDictionary>
<local:MyDataTemplateSelector x:Key="templateSelector"></local:MyDataTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
....
<control:CarouselView x:Name="carouselView" ItemTemplate="{StaticResource templateSelector}" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.