Carousel View in Xamarin Forms

With the release of Xamarin Forms 2.2.0, we now have the CarouselView, a replacement for the CarouselPage. CarouselPage will be marked as deprecated in a future release. As of this moment there isn’t any official documentation I can find on the CarouselView, hence it was a bit of trial and error but overall very easy to implement.

CarouselView Example

Benefits

  1. Can now be embedded in a page (big bonus)
  2. Is virtualized

Update: Due to instability in the Carousel View component in 2.2.0, Xamarin took this out of Xamarin Forms 2.3.0 and placed it in its own Nuget Package Xamarin.Forms.CarouselView. Xamarin have mentioned that this component will be added back into the main Xamarin.Forms nuget package once it is stable, though no date or version number was given.

The CarouselView is also now open source and can be viewed on GitHub at Xamarin.Forms.CarouselView

 

Adding Carousel View

Because the CarouselView is now a separate component as mentioned in the update above, we need to add it in to any page we want to use it on.

xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"

 

Carousel View XAML

On to the XAML, here is a very basic implementation of the CarouselView. As you can see it is just like using a control and a new view is created for each item in ItemsSource. ItemsSource will be a list of objects and you can then bind to their properties.

<ContentView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
   <control:CarouselView ItemsSource="{Binding MyDataSource}">
       <control:CarouselView.ItemTemplate>
           <DataTemplate>
                <Label Text="{Binding LabelText}" />
           </DataTemplate>
       </control:CarouselView.ItemTemplate>
   </control:CarouselView>
</ContentView>

 

UWP Setup

Again this is an extra step we need to take because it is temporarily as separate component but we need to add a resource to the Application.Resources in the UWP’s App.xaml.cs file as shown below.

<Application
     x:Class="DemoApp.UWP.App"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:platform="using:Xamarin.Forms.Platform"
     RequestedTheme="Dark">
     <Application.Resources>
         <DataTemplate x:Key="ItemTemplate">
               <platform:ItemControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
         </DataTemplate>
     </Application.Resources>
</Application>

Example Project: CarouselView Sample

Paging

CarouselView doesn’t come with a page indicator by default but you can wire one up with an event. You will need to create your own circle icons or buttons for tabs and you can update the selected status of them and even change the position by wiring up the following events.

I wrote a new post Carousel View Page Indicators that walks through adding your own indicators.

 

Behind the Scenes

Having a quick look at what this converts to natively;

  • WinRT/UWP = FlipView
  • Android = RecyclerView
  • iOS = UICollectionView
  • WinPhone = LongListSelector (but does not appear to be implemented)

Considering WinPhone Silverlight’s deprecated status I don’t think it will come to WinPhone Silverlight.


XAMARIN WEEKLY NEWSLETTER

Subscribe to a hand-picked round up of the best Xamarin development links every week. Published every Friday. Free.

Signup to Weekly Xamarin

* I do not maintain or run this newsletter, but I do recommend it.

Microsoft MVP | Xamarin MVP | Xamarin Forms Developer | Build Flutter

Related Posts

38 Comments

  1. guibesi

    Hello, I’m new with development in xamarin.forms, I’m needing help with example, I can not implement example.

    ItemsSource = “{Binding MyDataSource}” and Text = “{Binding LabelText}” where I retrieve these properties

    1. Adam Pedley

      These properties are just properties in your BindingContext. If you are using an MVVM approach, then it will be a property you create in your ViewModel. If not, whatever you set your BindingContext to (which could even be the codebehind .xaml.cs, then you would put it there).

  2. Dheeraj

    Hi,
    I’m Creating a carousel view.Only one card fits screen. Is there any solution where more than one card fits the screen?

    1. Adam Pedley

      If you are talking about displaying more than one item at a time in the list, then this isn’t possible with the current controls. I don’t think the native controls can even do this. As such you would need to create your own control from scratch for each native platform. Or combine multiple items together and show them on the same card, but make each card look like 2 or more.

  3. Motaz

    I am suffering from memory leaks issues with the carousel view control in Xamarin forms,
    the emulator keeps throwing out of memory exception while looping through the slides.
    is this a common issue with this control or there is something i should figure out,
    any help please?

    1. Adam Pedley

      Its not common, and I haven’t heard or experienced anything like that with the control. I suspect you might have images on your carousel views that are taking up a lot of memory and I guess this is on Android.

      Try with smaller images, to suit the screen size.

  4. abdullah

    i want the same sample but without binding for specific data on all pages ,, want to write custom xaml for each page how to do so ?

  5. chris

    I am currently working on a Xamarin.Forms(shared) application that uses a carousel view layout to create a list of waypoints to make a path. Each waypoint contains an image, a name, and a description. I need to be able to change these fields before going to the next point.

    I am currently creating a model to hold the values for each carousel view which I call WaypointModel. In order to add/ create a new carousel view I add a new Waypoint onto an ObservableCollection(). This model is then bound to the itemSource of the carousel view in xaml.

    My problem is that the UI is not updating when I add the next ObservableCollection item to the FIRST carousel view. For instance, if I click the add picture button it is not changing the image to the imageSource I have in the resources folder. However I have confirmed that it is changing the values within the model. The UI is simply not following. This problem is only present for the first carousel view. The same operation on any other screen works and changes the UI. If I go back to the first carousel after leaving it the UI will update. Functionality on this carousel will then act like the rest. Clicking to change the image will immediately change the UI.

    Is there some reason that the UI would not change for this first carousel item until it has left focus?

    Code:

    public PathContentPage()
    {
    InitializeComponent();
    CreateCarouselView();
    }

    private void CreateCarouselView()
    {
    colPts = new ListOfWaypointsModel();
    colPts.ListOfPts = new ObservableCollection();
    CarouselPaths.ItemSource = colPts.ListOfPts;
    colPts.ListOfPts.Add(new WaypointModel { isNotStart = false });
    }

    private void TakePicture_Clicked(object sender, System.EventArgs e)
    {
    var x = CarouselPaths.Item as WaypointModel;
    x.ImgSource = ImageSource.FromFile(“SaveIcon.png”);
    x.Name = “Name”;
    x.isPhotoVisible = true;
    //add next carousel view
    colPts.ListOfPts.Add(new WaypointModel { isNotStart = true });
    }

    Here is the xaml:

    … … …

    1. Chris

      I got the above problem working… hack; but working

      code:

      if(CarouselPaths.postion == 0)
      {
      InitializeComponent(); // ultimately forcing the carousel view to update
      CarouselPaths.ItemSource = Waypoints; // set to equal new values
      }

  6. Esu

    Hi ,

    i am trying to use the ItemTemplate (datatemplateselector) for CarouselView and it is not working.

    same code is working fine for Listview. any suggestions or ideas?

    regards
    Esu

    1. Adam Pedley

      What errors or output are you getting. The only difference between a listview and a carousel view for the DataTemplateSelector would be the CarouselView doesn’t need a ViewCell in its data template, you can put your root VisualElement directly in the DataTemplate.

  7. Ajay Singh

    I am facing an issue with carousel view. If I just touch and swap 5 % left or right on carousel view its open next carousel page. But I want to open next carousel page after minimum 50% swap (Just like Android Default Music player). How can I fix this ?, please suggest me. Thanks.

    1. Adam Pedley

      You won’t be able to do this unless you copy the renderer into your project and modify it manually for each platform. No options currently exist to do this out of the box.

      1. Ajay Singh

        Hi , I am stuck in this problem , please suggest me any Custom renderer code , how to handle this problem in custom renderer. Thanks

  8. Carey Patterson

    Hi Adam,

    I’m attempting to use the CarouselView in a Xamarin.Forms project, but I’m unable to get the UWP part working. I’ve created the using reference in the App.xaml on the UWP project, but the below errors are thrown regarding the “ItemControl” in the DataTemplate.

    1. The name “ItemControl” does not exist in the namespace “using:Xamarin.Forms.Platform”
    2. Unknown type “ItemControl” in XML namespace ‘using:Xamarin.Forms.Platform’
    3. The type ‘platform:ItemControl’ was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

    Any help is greatly appreciated.

    Thanks!

      1. Carey Patterson

        Yes I have, using NUGET for each project. The result was this:

        – The PCL project has: “CarouselView.FormsPlugin.Abstractions”
        – Android: “CarouselView.FormsPlugin.Abstractions” and “CarouselView.FormsPlugin.Android”
        – iOS: “CarouselView.FormsPlugin.Abstractions” and “CarouselView.FormsPlugin.iOS”
        – UWP: “CarouselView.FormsPlugin”

        1. Adam Pedley

          You are using a 3rd Party CarouselView plugin, not the Xamarin one.

          You will need to download Xamarin.Forms.CarouselView to follow the instructions in this article.

          1. Carey Patterson

            Thanks Adam!

            I didn’t see the official one in Nuget because I hadn’t selected to show pre-releases as well. I’m all good now. Thanks again!

  9. fairouz

    hello i wanted to control the picture also
    and display them in the carrousel it’s possible ? if you have idea please help me
    this is a screeshot for

    1. Adam Pedley

      I’m not sure I understand the question. You determine what is in the CarouselView by filling in the DataTemplate, as per the example above.

      There is an example project listed above, if you want to follow that link to see how it works.

  10. Anees

    Hi Adam,

    With the latest 2.3.0-pre2 version, I use below namespce declaraion
    xmlns:control=”clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView”

    no build error, however, while running getting the below exception.
    even after I already added the carouselview package in pcl, android and forms projects

    “control:CarouselView not found in xmlns clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView”

    Any help would be highly appreciated.

    1. Anees

      “To ensure that the CarouselView does not get “Linked-out” when compiling in release mode ensure that you are using Compiled XAML by adding the following code into the project’s AssemblyInfo.cs where your XAMLexists”

      using Xamarin.Forms.Xaml;
      [assembly: XamlCompilation(XamlCompilationOptions.Compile)]

  11. cypher

    Hello,

    I try to implement a CarouselView with the nuget packahe Xamarin.Forms.CarouselView (2.3.0-pre2). The carousel is fully functionnal on Android But on my iOS project it doesn’t work. Nothing appears on the screen. I don’t understand why. If some one have an idea ?

    My package is already install everywhere.

    Heres my Xaml Code:

  12. Arash

    Hi Adam. I’ve got ListViews inside each CarouselView items. It works good on iOS, however list view doesn’t scroll properly on Android. It seems CarouselView’s touch event has higher priority than ListView’s because ListView is a child view. Is there any solution to fix this problem?

    1. Adam Pedley

      Thanks for sharing the solution Arash. Just for quick reference, here is the code.

      Create a CustomRenderer on Android, and set the NestedScrollingEnabled property.

      protected override void OnElementChanged(ElementChangedEventArgs e)
      {
      base.OnElementChanged(e);

      if (e.NewElement != null)
      {
      var listView = this.Control as Android.Widget.ListView;
      listView.NestedScrollingEnabled = true;
      }
      }

  13. Nahid

    When I swipe through the carousel view, there is a small black coloured line appearing for a micro second on each view. How can it be disabled?

    1. Adam Pedley

      I don’t really think you could call that a feature, that needs disabling. It is most likely, that the device you are on, is struggling to update the UI fast enough, or you have a small black line as at the edge of your view, that you see when its swiped.

      Ensure you view covers the full width of the CarouselView, and that it doesn’t contain a black line at the end.

      If that isn’t the case, try reducing the view complexity of the CarouselView, to ease up on the UI rendering.

  14. Frank

    Hi Adam,

    do you know if it’s possible to turn off/on the swiping gesture?

    I have implemented the carousel view for swiping through images and added some gesture recognizers for tapping, pinching and panning (for zooming and to move the zoomed part of a picture), however, the swipe of the carousel view rules my pan gesture, i.e. I can only move up or down, left and right is taken from the carousel view.

    Thanks for your help in advance!

    Frank

  15. Felpower

    Hi Adam,

    I really like the CarouselView, but i am not able to add Indicators to my CarouselView, like you did, i used your code but its not working. The CarouselView it self works fine with Images and Labels.

    My Xaml looks like this

    while my C# Code looks like this (FYI i am using your Exrin MVVM) with an Observable Collection to use the CarouselView

    public class Promotions
    {
    public string ImageUrl { get; set; }

    public string Name { get; set; }

    public string Text { get; set; }

    public Command TapCommand { get; set; }

    public EventHandler TapClickEventHandler;

    public Promotions()
    {
    TapCommand = new Command(() => OnImageClicked());
    }

    public void OnImageClicked()
    {
    TapClickEventHandler?.Invoke(this, EventArgs.Empty);
    }
    }

    Promotions = new ObservableCollection
    {
    new Promotions
    {…ImageUrl = “”,
    Name = “!”,
    Text = “”,
    TapClickEventHandler = OnTapped….

    };
    }
    private int _position;

    public int Position { get { return _position; } set { _position = value; OnPropertyChanged(); } }

    1. Felpower

      carouselViewIndicators:CarouselIndicators Grid.Row=”1″ Grid.Column=”0″ IndicatorHeight=”16″ IndicatorWidth=”16″ UnselectedIndicator=”unselected_circle.png” SelectedIndicator=”selected_circle.png” Position=”{Binding Position}” ItemsSource=”{Binding ItemsSource}”

      This is my XAML, it wont let me post the full version

      I am using a ListView and a Grid inside the ListView