Category / Section
How to create a Carousel controls in Xaml
5 mins read
SfCarousel control allows navigating through image data in an interactive way so that they can be viewed or selected. We can create this control either using C# level code or in Xaml level code. Here we are going to write the carousel control creation with Xaml level code.
Creation of Carousel control:
Step 1: Import the carousel namespace
XAML
xmlns:syncfusion="clr-namespace:Syncfusion.SfCarousel.XForms;assembly=Syncfusion.SfCarousel.XForms"
Step 2: Initialize the carousel control as the content of content page
XAML
<syncfusion:SfCarousel x:Name="carousel" />
Step 3: Add the necessary properties on it.
XAML
<syncfusion:SfCarousel x:Name="carousel" Offset="20" RotationAngle="45 SelectedIndex="2" HeightRequest="400" WidthRequest="800" />
Step 4: Create a model view which holds image data in C# level
C#
class CarouselModel { public CarouselModel(string imagestr) { Image = imagestr; } private string _image; public string Image { get { return _image; } set { _image = value; } } }
Step 5: Populate carousel items collection in View model with the image data.
C#
public class CarouselViewModel { public CarouselViewModel() { ImageCollection.Add(new CarouselModel("image1.png")); ImageCollection.Add(new CarouselModel("image2.png")); ImageCollection.Add(new CarouselModel("image3.png")); ImageCollection.Add(new CarouselModel("image4.png")); ImageCollection.Add(new CarouselModel("image5.png")); } private List<CarouselModel> imageCollection = new List<CarouselModel>(); public List<CarouselModel> ImageCollection { get { return imageCollection; } set { imageCollection = value; } } }
The following finalized code will illustrate the way to create a carousel control with xaml code.
XAML
<? xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns = "http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:syncfusion="clr-namespace:Syncfusion.SfCarousel.XForms;assembly=Syncfusion.SfCarousel.XForms" x:Class="GettingStarted.CarouselControlPage"> <ContentPage.Resources> <ResourceDictionary> <DataTemplate x:Key="itemTemplate"> <Image Source = "{Binding Image}" Aspect="AspectFit"/> </DataTemplate> </ResourceDictionary> </ContentPage.Resources> <ContentPage.Content> <syncfusion:SfCarousel x:Name="carousel" ItemTemplate="{StaticResource itemTemplate}" DataSource="{Binding ImageCollection}" SelectedIndex="2" RotationAngle="45" HeightRequest="400" WidthRequest="800" /> </ContentPage.Content> </ContentPage>