This section explains how to improve the performance of the .NET MAUI Carousel View using the UI Virtualization feature in the SfCarousel control. The EnableVirtualization property helps reduce memory usage and improve scrolling performance by creating and displaying only the visible items instead of rendering all carousel items at once.
Define the SfCarousel control and enable UI virtualization by setting the EnableVirtualization property to True. This ensures that only the required carousel items are generated and maintained in the visual tree, resulting in better performance when working with large collections.
<carousel:SfCarousel x:Name="carousel"
ItemsSource="{Binding ImageCollection}"
EnableVirtualization="True"
ItemHeight="200"
ItemWidth="200"
ItemSpacing="2"
ViewMode="Linear">
<carousel:SfCarousel.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Image}"
Aspect="AspectFit"/>
</DataTemplate>
</carousel:SfCarousel.ItemTemplate>
</carousel:SfCarousel>
Create a view model that contains a collection of images and bind it to the carousel. When EnableVirtualization is set to True, the carousel generates only the items that are currently visible on the screen and reuses item views as the user navigates through the collection. This improves rendering efficiency and provides a smoother user experience, especially when displaying a large number of items.
// Model
public class CarouselModel
{
public CarouselModel(string imageString)
{
Image = imageString;
}
private string _image;
public string Image
{
get { return _image; }
set { _image = value; }
}
}
// ViewModel
public class CarouselViewModel : INotifyPropertyChanged
{
public CarouselViewModel()
{
ImageCollection.Add(new CarouselModel("person1.jpg"));
ImageCollection.Add(new CarouselModel("person2.jpg"));
ImageCollection.Add(new CarouselModel("person3.jpg"));
ImageCollection.Add(new CarouselModel("person4.jpg"));
ImageCollection.Add(new CarouselModel("person5.jpg"));
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;
OnPropertyChanged(nameof(ImageCollection));
}
}
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}