Category / Section
How to render a custom content to a Carousel
1 min read
We can render the custom view by using “ItemTemplate” property in Carousel. The following steps will help to render the custom view.
Step1: Add needed assemblies to have the carousel control
Step2: Create a model view which holds the data (CarouselModel)
Step 3: ItemTemplate property of carousel is used to customize the contents of carousel items. So, assign the collection of your template view to carousel datasource.
The below code illustrates the way to render a custom content to carousel
Code snippet:
public partial class KBSolutionPage : ContentPage { public KBSolutionPage() { InitializeComponent(); //Initialize the carousel control SfCarousel sfCarousel = new SfCarousel(); if (Device.OS == TargetPlatform.Android) { sfCarousel.ItemWidth = 170; sfCarousel.ItemHeight = 250; } if (Device.OS == TargetPlatform.iOS) { sfCarousel.ItemWidth = 150; sfCarousel.ItemHeight = 300; } var carouselModel = new List<CarouselModel> { new CarouselModel ("Button1","Label1"), new CarouselModel ("Button2","Label2"), new CarouselModel ("Button3","Label3"), new CarouselModel ("Button4","Label4"), new CarouselModel ("Button5","Label5") }; var carouselDataTemplate = new DataTemplate(() => { var stack = new StackLayout(); var buttonText = new Button() { TextColor = Color.Green, HeightRequest = 200, WidthRequest = 200 }; buttonText.SetBinding(Button.TextProperty, "ButtonString"); var labelText = new Label() { TextColor = Color.Red, HorizontalOptions = LayoutOptions.Center }; labelText.SetBinding(Label.TextProperty, "LabelString"); stack.Children.Add(buttonText); stack.Children.Add(labelText); return stack; }); sfCarousel.ItemTemplate = carouselDataTemplate; sfCarousel.DataSource = carouselModel; this.Content = sfCarousel; } } public class CarouselModel { public CarouselModel(string buttonstr, string labelstr) { ButtonString = buttonstr; LabelString = labelstr; } private string buttonString; public string ButtonString { get { return buttonString; } set { buttonString = value; } } private string labelString; public string LabelString { get { return labelString; } set { labelString = value; } } } }
Output: