Using CarouselView Data In Xamarin-Forms

carouselview

What is CarouselView?

CarouselView is a view that displays data in a scrollable style that allows users to swipe through a group of objects. CarouselView displays its items in a horizontal arrangement by default. A single item will be presented on the screen, with swipe gestures allowing for forwarding and backward navigation through the collection. In addition, indicators that indicate each item in the CarouselView can be displayed.

Introduction

The following properties define the data to be presented as well as the design of the CarouselView:

  • ItemsSource is of type IEnumerable and has a default value of null. It provides the collection of items to be displayed.
  • The template to apply to each item in the collection of items to be presented is specified by ItemTemplate, which is of type DataTemplate.

These properties are backed by BindableProperty objects, which means they can be data binding targets. As the user scrolls, CarouselView offers incremental data virtualization. See the following equations incrementally for additional information.

Populate CarouselView with data

Setting the ItemsSource property of a CarouselView to any collection that implements IEnumerable populates it with data. CarouselView shows items horizontally by default. The ItemsSource property of a CarouselView can be bound to an IEnumerable collection using data binding. The Binding markup extension in XAML allows you to do this:

Xaml Code:

<CarouselView ItemsSource=”{Binding Monkeys}” />

C# Code:

CarouselView carouselView = new CarouselView();

carouselView.SetBinding(ItemsView.ItemsSourceProperty, “Monkeys”);

Define item appearance

Setting the CarouselView allows you to customize the appearance of each item in the CarouselView. To add a DataTemplate’s ItemTemplate property:

XAML Code:

<CarouselView ItemsSource=”{Binding Monkeys}”>

    <CarouselView.ItemTemplate>

        <DataTemplate>

            <StackLayout>

                <Frame HasShadow=”True”

                       BorderColor=”DarkGray”

                       CornerRadius=”5″

                       Margin=”20″

                       HeightRequest=”300″

                       HorizontalOptions=”Center”

                       VerticalOptions=”CenterAndExpand”>

                    <StackLayout>

                        <Label Text=”{Binding Name}”

                               FontAttributes=”Bold”

                               FontSize=”Large”

                               HorizontalOptions=”Center”

                               VerticalOptions=”Center” />

                        <Image Source=”{Binding ImageUrl}”

                               Aspect=”AspectFill”

                               HeightRequest=”150″

                               WidthRequest=”150″

                               HorizontalOptions=”Center” />

                        <Label Text=”{Binding Location}”

                               HorizontalOptions=”Center” />

                        <Label Text=”{Binding Details}”

                               FontAttributes=”Italic”

                               HorizontalOptions=”Center”

                               MaxLines=”5″

                               LineBreakMode=”TailTruncation” />

                    </StackLayout>

                </Frame>

            </StackLayout>

        </DataTemplate>

    </CarouselView.ItemTemplate>

</CarouselView>

C# Code:

CarouselView carouselView = new CarouselView();

carouselView.SetBinding(ItemsView.ItemsSourceProperty, “Monkeys”);

carouselView.ItemTemplate = new DataTemplate(() =>

{

    Label nameLabel = new Label { … };

    nameLabel.SetBinding(Label.TextProperty, “Name”);

    Image image = new Image { … };

    image.SetBinding(Image.SourceProperty, “ImageUrl”);

    Label locationLabel = new Label { … };

    locationLabel.SetBinding(Label.TextProperty, “Location”);

    Label detailsLabel = new Label { … };

    detailsLabel.SetBinding(Label.TextProperty, “Details”);

    StackLayout stackLayout = new StackLayout

    {

        Children = { nameLabel, image, locationLabel, detailsLabel }

    };

    Frame frame = new Frame { … };

    StackLayout rootStackLayout = new StackLayout

    {

        Children = { frame }

    };

    return rootStackLayout;

});

Each item in the CarouselView’s look is determined by the elements supplied in the DataTemplate. In this example, a StackLayout manages the layout within the DataTemplate, and the data is shown using an Image object and three Label objects, all of which bind to Monkey class properties:

C# Code:

public class Monkey

{

    public string Name { get; set; }

    public string Location { get; set; }

    public string Details { get; set; }

    public string ImageUrl { get; set; }

}

Choose item appearance at runtime

Setting the CarouselView allows developers will choose the appearance of each item in the CarouselView at runtime based on the item value. A DataTemplateSelector item’s ItemTemplate property is as continues to follow:

XAML Code:

<ContentPage …

             xmlns:controls=”clr-namespace:CarouselViewDemos.Controls”

             x:Class=”CarouselViewDemos.Views.HorizontalLayoutDataTemplateSelectorPage”>

    <ContentPage.Resources>

        <DataTemplate x:Key=”AmericanMonkeyTemplate”>

        </DataTemplate>

        <DataTemplate x:Key=”OtherMonkeyTemplate”>

        </DataTemplate>

        <controls:MonkeyDataTemplateSelector x:Key=”MonkeySelector”

                                             AmericanMonkey=”{StaticResource AmericanMonkeyTemplate}”

                                             OtherMonkey=”{StaticResource OtherMonkeyTemplate}” />

    </ContentPage.Resources>

    <CarouselView ItemsSource=”{Binding Monkeys}”

                  ItemTemplate=”{StaticResource MonkeySelector}” />

</ContentPage>

C# Code:

CarouselView carouselView = new CarouselView

{

    ItemTemplate = new MonkeyDataTemplateSelector { … }

};

carouselView.SetBinding(ItemsView.ItemsSourceProperty, “Monkeys”);

A MonkeyDataTemplateSelector object is used as the ItemTemplate attribute. The MonkeyDataTemplateSelector class is demonstrated in the following example:

C# Code:

public class MonkeyDataTemplateSelector : DataTemplateSelector

{

    public DataTemplate AmericanMonkey { get; set; }

    public DataTemplate OtherMonkey { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)

    {

        return ((Monkey)item).Location.Contains(“America”) ? AmericanMonkey : OtherMonkey;

    }

}

The AmericanMonkey and OtherMonkey DataTemplate attributes of the MonkeyDataTemplateSelector class are set to distinct data templates. When the monkey name contains the word “America,” the OnSelectTemplate override returns the AmericanMonkey template. When the monkey’s name does not contain the word “America,” the OnSelectTemplate override returns the OtherMonkey template, with its data greyed out:

Display Indicators

Next to the CarouselView, indicators that reflect the number of items and current position in the CarouselView can be displayed. The IndicatorView control can be used to accomplish this:

XAML Code:

<StackLayout>

    <CarouselView ItemsSource=”{Binding Monkeys}”

                  IndicatorView=”indicatorView”>

        <CarouselView.ItemTemplate>

            <!– DataTemplate that defines item appearance –>

        </CarouselView.ItemTemplate>

    </CarouselView>

    <IndicatorView x:Name=”indicatorView”

                   IndicatorColor=”LightGray”

                   SelectedIndicatorColor=”DarkGray”

                   HorizontalOptions=”Center” />

</StackLayout>

The IndicatorView is displayed beneath the CarouselView in this example, and each item in the CarouselView has an indication. By establishing the CarouselView, the IndicatorView is filled with data. The IndicatorView object’s IndicatorView attribute is set to true. Each indication is a light grey circle, with the exception of the dark grey indicator that symbolizes the current item in the CarouselView:

Context Menus

In the Roadmap of Xamarin.Forms, a SwipeView is something which reveals the context menu with a swipe gesture, is supported by CarouselView for data context menus. The SwipeView is a container control that wraps around a piece of content and provides context menu options for it. As a result, context menus for a CarouselView are accomplished by constructing a SwipeView that defines the content that the SwipeView wraps around, as well as the context menu items displayed by the swipe gesture. This is accomplished by including a SwipeView in the DataTemplate, which defines the look of each data item in the CarouselView:

XAML Code:

<CarouselView x:Name=”carouselView”

              ItemsSource=”{Binding Monkeys}”>

    <CarouselView.ItemTemplate>

        <DataTemplate>

            <StackLayout>

                    <Frame HasShadow=”True”

                           BorderColor=”DarkGray”

                           CornerRadius=”5″

                           Margin=”20″

                           HeightRequest=”300″

                           HorizontalOptions=”Center”

                           VerticalOptions=”CenterAndExpand”>

                        <SwipeView>

                            <SwipeView.TopItems>

                                <SwipeItems>

                                    <SwipeItem Text=”Favorite”

                                               IconImageSource=”favorite.png”

                                               BackgroundColor=”LightGreen”

                                               Command=”{Binding Source={x:Reference carouselView}, Path=BindingContext.FavoriteCommand}”

                                               CommandParameter=”{Binding}” />

                                </SwipeItems>

                            </SwipeView.TopItems>

                            <SwipeView.BottomItems>

                                <SwipeItems>

                                    <SwipeItem Text=”Delete”

                                               IconImageSource=”delete.png”

                                               BackgroundColor=”LightPink”

                                               Command=”{Binding Source={x:Reference carouselView}, Path=BindingContext.DeleteCommand}”

                                               CommandParameter=”{Binding}” />

                                </SwipeItems>

                            </SwipeView.BottomItems>

                            <StackLayout>

                                <!– Define item appearance –>

                            </StackLayout>

                        </SwipeView>

                    </Frame>

            </StackLayout>

        </DataTemplate>

    </CarouselView.ItemTemplate>

</CarouselView>

C#  Code:

CarouselView carouselView = new CarouselView();

carouselView.SetBinding(ItemsView.ItemsSourceProperty, “Monkeys”);

carouselView.ItemTemplate = new DataTemplate(() =>

{

    StackLayout stackLayout = new StackLayout();

    Frame frame = new Frame { … };

    SwipeView swipeView = new SwipeView();

    SwipeItem favoriteSwipeItem = new SwipeItem

    {

        Text = “Favorite”,

        IconImageSource = “favorite.png”,

        BackgroundColor = Color.LightGreen

    };

    favoriteSwipeItem.SetBinding(MenuItem.CommandProperty, new Binding(“BindingContext.FavoriteCommand”, source: carouselView));

    favoriteSwipeItem.SetBinding(MenuItem.CommandParameterProperty, “.”);

    SwipeItem deleteSwipeItem = new SwipeItem

    {

        Text = “Delete”,

        IconImageSource = “delete.png”,

        BackgroundColor = Color.LightPink

    };

    deleteSwipeItem.SetBinding(MenuItem.CommandProperty, new Binding(“BindingContext.DeleteCommand”, source: carouselView));

    deleteSwipeItem.SetBinding(MenuItem.CommandParameterProperty, “.”);

    swipeView.TopItems = new SwipeItems { favoriteSwipeItem };

    swipeView.BottomItems = new SwipeItems { deleteSwipeItem };

    StackLayout swipeViewStackLayout = new StackLayout { … };

    swipeView.Content = swipeViewStackLayout;

    frame.Content = swipeView;

    stackLayout.Children.Add(frame);

    return stackLayout;

});

The SwipeView content in this example is a StackLayout that specifies the layout of every item in the CarouselView that is surrounded by a Frame. The swipe items, which are revealed when the control is swiped from the top and bottom, are used to conduct actions on the SwipeView content:

The SwipeView content in this example is a StackLayout that specifies the layout of every item in the CarouselView that is surrounded by a Frame. The swipe items, which are revealed when the control is swiped from the top and bottom, are used to conduct actions on the SwipeView content. Furthermore, after a swipe item is used, the swipe items are hidden and the SwipeView content is re-displayed. These habits, however, can be altered.

Conclusion

In this blog, what we have learned is all about the data CarouselView, how to populate CarouselView with data and an example, item appearance and an example, item appearance in real-time with an example, display indication, and context menus with applications in this blog.

Author Bio:

Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.Technocrat and entrepreneur of a reputed Word Add-in Development Company with years of experience in building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

Leave a Reply

Your email address will not be published. Required fields are marked *