Xamarin.Forms CollectionView Tutorial
Before attempting this tutorial, you should have successfully completed the:
- Build your first Xamarin.Forms app quickstart.
- StackLayout tutorial.
- Grid tutorial.
- Label tutorial.
- Image tutorial.
In this tutorial, you learn how to:
- Create a Xamarin.Forms
CollectionViewin XAML. - Populate the
CollectionViewwith data. - Respond to
CollectionViewitems being selected. - Customize the appearance of
CollectionViewitems.
You will use Visual Studio 2019, or Visual Studio for Mac, to create a simple application that demonstrates how to customize the appearance of a CollectionView. The following screenshots show the final application:
Create a collectionview
To complete this tutorial you should have Visual Studio 2019 (latest release), with the Mobile development with .NET workload installed. In addition, you will require a paired Mac to build the tutorial application on iOS. For information about installing the Xamarin platform, see Installing Xamarin. For information about connecting Visual Studio 2019 to a Mac build host, see Pair to Mac for Xamarin.iOS development.
Launch Visual Studio, and create a new blank Xamarin.Forms app named CollectionViewTutorial.
Important
The C# and XAML snippets in this tutorial requires that the solution is named CollectionViewTutorial. Using a different name will result in build errors when you copy code from this tutorial into the solution.
For more information about the .NET Standard library that gets created, see Anatomy of a Xamarin.Forms application in the Xamarin.Forms Quickstart Deep Dive.
In Solution Explorer, in the CollectionViewTutorial project, double-click MainPage.xaml to open it. Then, in MainPage.xaml, remove all of the template code and replace it with the following code:
<?xml version="1.0" encoding="utf-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CollectionViewTutorial.MainPage"> <StackLayout Margin="20,35,20,20"> <CollectionView> <CollectionView.ItemsSource> <x:Array Type="{x:Type x:String}"> <x:String>Baboon</x:String> <x:String>Capuchin Monkey</x:String> <x:String>Blue Monkey</x:String> <x:String>Squirrel Monkey</x:String> <x:String>Golden Lion Tamarin</x:String> <x:String>Howler Monkey</x:String> <x:String>Japanese Macaque</x:String> </x:Array> </CollectionView.ItemsSource> </CollectionView> </StackLayout> </ContentPage>This code declaratively defines the user interface for the page, which consists of a
CollectionViewin aStackLayout. TheCollectionView.ItemsSourceproperty specifies the items to display, which are defined in an array of strings.In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator:
In Visual Studio, stop the application.
Populate with data
A CollectionView is populated with data using the ItemsSource property, which is of type IEnumerable. The previous step populated the CollectionView in XAML with an array of strings. However, typically a CollectionView will be populated with data from a collection, defined in code, that implements IEnumerable.
In this exercise, you will modify the CollectionViewTutorial project to populate the CollectionView with data from a collection of objects stored in a List.
In Solution Explorer, in the CollectionViewTutorial project, add a class named
Monkeythat contains the following code:public class Monkey { public string Name { get; set; } public string Location { get; set; } public string ImageUrl { get; set; } public override string ToString() { return Name; } }This code defines a
Monkeyobject that stores a name, location, and url of an image that represents the monkey. In addition, the class overrides theToStringmethod to return theNameproperty.In Solution Explorer, in the CollectionViewTutorial project, expand MainPage.xaml and double-click MainPage.xaml.cs to open it. Then, in MainPage.xaml.cs, remove all of the template code and replace it with the following code:
using System.Collections.Generic; using Xamarin.Forms; namespace CollectionViewTutorial { public partial class MainPage : ContentPage { public IList<Monkey> Monkeys { get; private set; } public MainPage() { InitializeComponent(); Monkeys = new List<Monkey>(); Monkeys.Add(new Monkey { Name = "Baboon", Location = "Africa & Asia", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg" }); Monkeys.Add(new Monkey { Name = "Capuchin Monkey", Location = "Central & South America", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg" }); Monkeys.Add(new Monkey { Name = "Blue Monkey", Location = "Central and East Africa", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/BlueMonkey.jpg/220px-BlueMonkey.jpg" }); Monkeys.Add(new Monkey { Name = "Squirrel Monkey", Location = "Central & South America", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/220px-Saimiri_sciureus-1_Luc_Viatour.jpg" }); Monkeys.Add(new Monkey { Name = "Golden Lion Tamarin", Location = "Brazil", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Golden_lion_tamarin_portrait3.jpg/220px-Golden_lion_tamarin_portrait3.jpg" }); Monkeys.Add(new Monkey { Name = "Howler Monkey", Location = "South America", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Alouatta_guariba.jpg/200px-Alouatta_guariba.jpg" }); Monkeys.Add(new Monkey { Name = "Japanese Macaque", Location = "Japan", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Macaca_fuscata_fuscata1.jpg/220px-Macaca_fuscata_fuscata1.jpg" }); Monkeys.Add(new Monkey { Name = "Mandrill", Location = "Southern Cameroon, Gabon, Equatorial Guinea, and Congo", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Mandrill_at_san_francisco_zoo.jpg/220px-Mandrill_at_san_francisco_zoo.jpg" }); Monkeys.Add(new Monkey { Name = "Proboscis Monkey", Location = "Borneo", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Proboscis_Monkey_in_Borneo.jpg/250px-Proboscis_Monkey_in_Borneo.jpg" }); Monkeys.Add(new Monkey { Name = "Red-shanked Douc", Location = "Vietnam, Laos", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Portrait_of_a_Douc.jpg/159px-Portrait_of_a_Douc.jpg" }); Monkeys.Add(new Monkey { Name = "Gray-shanked Douc", Location = "Vietnam", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Cuc.Phuong.Primate.Rehab.center.jpg/320px-Cuc.Phuong.Primate.Rehab.center.jpg" }); Monkeys.Add(new Monkey { Name = "Golden Snub-nosed Monkey", Location = "China", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Golden_Snub-nosed_Monkeys%2C_Qinling_Mountains_-_China.jpg/165px-Golden_Snub-nosed_Monkeys%2C_Qinling_Mountains_-_China.jpg" }); Monkeys.Add(new Monkey { Name = "Black Snub-nosed Monkey", Location = "China", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/RhinopitecusBieti.jpg/320px-RhinopitecusBieti.jpg" }); Monkeys.Add(new Monkey { Name = "Tonkin Snub-nosed Monkey", Location = "Vietnam", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9c/Tonkin_snub-nosed_monkeys_%28Rhinopithecus_avunculus%29.jpg/320px-Tonkin_snub-nosed_monkeys_%28Rhinopithecus_avunculus%29.jpg" }); Monkeys.Add(new Monkey { Name = "Thomas's Langur", Location = "Indonesia", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Thomas%27s_langur_Presbytis_thomasi.jpg/142px-Thomas%27s_langur_Presbytis_thomasi.jpg" }); Monkeys.Add(new Monkey { Name = "Purple-faced Langur", Location = "Sri Lanka", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Semnopithèque_blanchâtre_mâle.JPG/192px-Semnopithèque_blanchâtre_mâle.JPG" }); Monkeys.Add(new Monkey { Name = "Gelada", Location = "Ethiopia", ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Gelada-Pavian.jpg/320px-Gelada-Pavian.jpg" }); BindingContext = this; } } }This code defines a
Monkeysproperty of typeIList<Monkey>and initializes it to an empty list in the class constructor.Monkeyobjects are then added to theMonkeyscollection, and theBindingContextof the page is set to theMainPageobject. For more information about theBindingContextproperty, see Bindings with a Binding Context in the Xamarin.Forms Data Binding guide.Important
The
BindingContextproperty is inherited through the visual tree. Therefore, because it's been set on theContentPageobject, child objects of theContentPageinherit its value, including theCollectionView.In MainPage.xaml, modify the
CollectionViewdeclaration to set theItemsSourceproperty to theMonkeyscollection:<CollectionView ItemsSource="{Binding Monkeys}" />This code data binds the
ItemsSourceproperty to theMonkeyscollection. At runtime, theCollectionViewwill look at itsBindingContextfor theMonkeyscollection, and it will be populated with data from this collection. For more information about data binding, see Xamarin.Forms Data Binding.In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote OS simulator or Android emulator:
The
CollectionViewis displaying theNameproperty for eachMonkeyin theMonkeyscollection. This is because, by default, theCollectionViewcalls theToStringmethod when displaying the objects from a collection (which has been overridden in theMonkeyclass to return theNameproperty value).In Visual Studio, stop the application.
Respond to item selection
In MainPage.xaml, modify the
CollectionViewdeclaration so that it sets theSelectionModeproperty toSingle, and sets a handler for theSelectionChangedevent:<CollectionView ItemsSource="{Binding Monkeys}" SelectionMode="Single" SelectionChanged="OnSelectionChanged" />This code sets enables single item selection in the
CollectionView, and sets theSelectionChangedevent to an event handler namedOnSelectionChanged. The event handler will be created in the next step.In Solution Explorer, in the CollectionViewTutorial project, expand MainPage.xaml and double-click MainPage.xaml.cs to open it. Then, in MainPage.xaml.cs, add the
OnSelectionChangedevent handler to the class:void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { Monkey selectedItem = e.CurrentSelection[0] as Monkey; }When an item in the
CollectionViewis selected, theSelectionChangedevent is fired, which executes theOnSelectionChangedmethod. Thesenderargument to the method is theCollectionViewobject responsible for firing the event, which can be used to access theCollectionViewobject. TheSelectionChangedEventArgsargument to theOnSelectionChangedmethod provides the selected item.In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator:
Set a breakpoint in the
OnSelectionChangedevent handler and select an item in theCollectionView. Examine the value of theselectedItemvariable, to ensure it contains the data for your selected item.In Visual Studio, stop the application.
For more information about item selection, see Xamarin.Forms CollectionView selection.
Customize item appearance
Previously, the CollectionView was populated with data using data binding. However, despite data binding to a collection, where each object in the collection defined multiple items of data, only a single item of data was displayed per object (the Name property of the Monkey object).
In this exercise, you will modify the CollectionViewTutorial project so that the CollectionView displays multiple items of data in each row.
In MainPage.xaml, modify the
CollectionViewdeclaration to customize the appearance of each item of data:<CollectionView ItemsSource="{Binding Monkeys}" SelectionMode="Single" SelectionChanged="OnSelectionChanged"> <CollectionView.ItemTemplate> <DataTemplate> <Grid Padding="10" RowDefinitions="Auto, *" ColumnDefinitions="Auto, *"> <Image Grid.RowSpan="2" Source="{Binding ImageUrl}" Aspect="AspectFill" HeightRequest="60" WidthRequest="60" /> <Label Grid.Column="1" Text="{Binding Name}" FontAttributes="Bold" /> <Label Grid.Row="1" Grid.Column="1" Text="{Binding Location}" VerticalOptions="End" /> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>This code sets the
CollectionView.ItemTemplateproperty to aDataTemplate, which defines the appearance of each item in theCollectionView. The child of theDataTemplateis aGrid, which contains anImageobject and twoLabelobjects. TheImageobject data binds itsSourceproperty to theImageUrlproperty of eachMonkeyobject, while theLabelobjects bind theirTextproperties to theNameandLocationproperties of eachMonkeyobject.For more information about
CollectionViewitem appearance, see Define item appearance. For more information about data templates, see Xamarin.Forms Data Templates.In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside your chosen remote iOS simulator or Android emulator:
In Visual Studio, stop the application.
Congratulations!
Congratulations on completing this tutorial, where you learned how to:
- Create a Xamarin.Forms
CollectionViewin XAML. - Populate the
CollectionViewwith data. - Respond to
CollectionViewitems being selected. - Customize the appearance of
CollectionViewitems.
Next steps
To learn more about the basics of creating mobile applications with Xamarin.Forms, continue to the Pop-ups tutorial.
Related links
Have an issue with this section? If so, please give us some feedback so we can improve this section.
Feedback
Issottometti u ara feedback għal




