How to perform an operation while changing the CarouselItem?
21 Jul 20264 minutes to read
We can perform an operation when the selected carousel item changes by handling the SelectionChanged event. The SelectionChanged event provides the previously selected item through e.OldItem and the currently selected item through e.NewItem.
The following XAML sample binds Carousel to an ImageCollection and handles the SelectionChanged event.
<carousel:SfCarousel x:Name="carousel"
ItemsSource="{Binding ImageCollection}"
ItemHeight="170"
ItemWidth="270"
SelectionChanged="Carousel_SelectionChanged">
<carousel:SfCarousel.BindingContext>
<local:CarouselViewModel/>
</carousel:SfCarousel.BindingContext>
<carousel:SfCarousel.ItemTemplate>
<DataTemplate >
<Image Source="{Binding Image}"
Aspect="AspectFit"/>
</DataTemplate>
</carousel:SfCarousel.ItemTemplate>
</carousel:SfCarousel>CarouselViewModel carouselViewModel = new CarouselViewModel();
SfCarousel carousel = new SfCarousel()
{
ItemHeight = 170,
ItemWidth = 270,
BindingContext = carouselViewModel,
ItemsSource = carouselViewModel.ImageCollection,
ItemTemplate = new DataTemplate(() =>
{
var image = new Image();
image.SetBinding(Image.SourceProperty, "Image");
return image;
}),
};
carousel.SelectionChanged += Carousel_SelectionChanged;// Model
public class CarouselModel
{
public CarouselModel(string imageString)
{
Image = imageString;
}
private string _image;
public string Image
{
get { return _image; }
set { _image = value; }
}
}
//View Model
public class CarouselViewModel
{
public CarouselViewModel()
{
ImageCollection.Add(new CarouselModel("carousel_person1.png"));
ImageCollection.Add(new CarouselModel("carousel_person2.png"));
ImageCollection.Add(new CarouselModel("carousel_person3.png"));
ImageCollection.Add(new CarouselModel("carousel_person4.png"));
ImageCollection.Add(new CarouselModel("carousel_person5.png"));
}
private List<CarouselModel> imageCollection = new List<CarouselModel>();
public List<CarouselModel> ImageCollection
{
get { return imageCollection; }
set { imageCollection = value; }
}
}The SelectionChanged event can be handled in C# as follows:
// Triggered when the selection changes in the carousel.
private void Carousel_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is SfCarousel sfCarousel)
{
int count = sfCarousel.SelectedIndex + 1;
this.DisplayAlert("SelectionChanged", "Carousel item " + count + " has been selected.", "OK");
}
}