How To Work With CollectionView in Xamarin Forms

Shankar Madeshvaran
Developer in Making
6 min readNov 11, 2019

--

With Xamarin.Forms 4.3, we can now use CollectionView in your apps without the need for the Experimental flag enabled.

Photo by Farzad Nazifi on Unsplash

CollectionView is a flexible and performant view for presenting lists of data using different layout specifications. It aims to provide a more flexible, and performant alternative to ListView.

With Xamarin.Forms 4.3 stable release marks the removal of the experimental flag from collectionView as it moves into stable status. CollectionView is built to be fast, uses modern, native controls, and removes the concept of ViewCells.

CollectionView is available on iOS and Android, but is only partially available on the Universal Windows Platform.

In this article, we’ll dive into some of the main features of CollectionView in Xamarin Forms .We’ll focus specifically on how set Data, Layout, Selection and Scrolling to collection view.

You’ll learn about:

  • How CollectionView differs from ListView
  • How to populated CollectionView with Data.
  • How the work with custom Layout
  • How to work with Selection of collection view cells
  • How to work with Horizontal and Vertical Scrolling

Ready? Let’s go.

1) How CollectionView differs from ListView

  • CollectionView has a flexible layout model, which allows data to be presented vertically or horizontally, in a list or a grid. Both Vertical and Horizontal scrolling is supported.
  • If you want to display things vertically use ListView, if you want do display things with your own style use CollectionView
  • By default, CollectionView selection is disabled. However, single (SelectedItem) and multiple selection (SelectionMode) can be enabled.
  • CollectionView does not include built-in separators such as SeparatorColor, SeparatorVisibility. These can be provided, if desired, in the item template.
  • CollectionView has no concept of cells such as TextCell, ImageCell, ViewCell. Instead, a data template is used to define the appearance of each item of data in the list.
  • ContextActions are currently unsupported. Maybe be available to developers in future releases.
  • Pull to refresh functionality is supported by setting a collectionView as the child of a RefreshView

2) Populating CollectionView with Data

A CollectionView is populated with data by setting its ItemsSource property to any collection that implements IEnumerable. The appearance of each item in the list can be defined by setting the ItemTemplate property to a DataTemplate.

Create a Model Class

public class Contact
{
public string FirstName { get; set;}
public string LastName { get;set; }
public string UserId { get;set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PhotoUrl { get; set; }
public string Country { get; set; }
public string FullName => FirstName + " " + LastName;
}
  • I have created a model class named Contact
  • Model class has some basic details such as Name, Email, Phone, Profile etc.

Provide Data To Populate CollectionView

  • CollectionView can be populated with data by using data binding to bind its ItemsSource property to an IEnumerable collection.
  • We can use static data or fetch data from REST API, I have used static data to populate CollectionView by creating a new class Contacts
  • This class return data of IEnumerable Object
  • ItemsSource, of type IEnumerable, specifies the collection of items to be displayed, and has a default value of null.
public class Contacts
{
public static IEnumerable<Contact> Get()
{
return new List<Contact>
{
new Contact() {UserId="1", FirstName="Contact", LastName="One", Email="contact.one@gmail.com", Phone="1234131332", PhotoUrl="profile01.png",Country="India" },
new Contact() {UserId="2", FirstName="Contact", LastName="Two", Email="contact.two@gmail.com", Phone="1289413132", PhotoUrl="profile02.png",Country="India" },
new Contact() {UserId="3",FirstName="Contact", LastName="Three",Email="contact.three@gmail.com",Phone="4234242235", PhotoUrl="profile03.png",Country="India" },
new Contact() {UserId="4", FirstName="Contact", LastName="Four", Email="contact.four@gmail.com",Phone="6443245633", PhotoUrl="profile04.png",Country="India" },
new Contact() {UserId="5", FirstName="Contact", LastName="Five", Email="contact.five@gmail.com",Phone="4234242235", PhotoUrl="profile05.png",Country="India" },
new Contact() {UserId="6", FirstName="Contact", LastName="Six", Email="contact.six@gmail.com",Phone="2344324443", PhotoUrl="profile06.png",Country="India" },
new Contact() {UserId="7", FirstName="Contact", LastName="Seven",Email="contact.seven@gmail.com",Phone="2344234234", PhotoUrl="profile01.png",Country="India" },
new Contact() {UserId="8", FirstName="Contact", LastName="Eight",Email="contact.eight@gmail.com",Phone="4234242235", PhotoUrl="profile02.png",Country="India" },
};
}
}
  • After providing static values, we need to set this to collectionView , we can easily populate a collectionView by given Name reference to it.

xaml

<CollectionView x:Name="collectionViewListHorizontal" >  </CollectionView>

xaml.cs

   public List<Contact> AllContacts { get; set; }   public ContactsPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
AllContacts = new List<Contact>(Contacts.Get());
collectionViewListHorizontal.ItemsSource = AllContacts;
}
  • We have populated collectionView by setting contacts to ItemSource
  • Now we need to develop an custom template to show data

3) Working with Custom Layout

  • ItemTemplate, of type DataTemplate, specifies the template to apply to each item in the collection of items to be displayed.
  • CollectionView has no concept of cells. Instead, a data template is used to define the appearance of each item of data in the list.
  • The appearance of each item in the CollectionView can be defined by setting the CollectionView.ItemTemplate property to a DataTemplate:
Customized Data Template — CollectionView in Xaml
  • The above code contains Xaml custom data template to show contact details.
  • By using Binding property, we set the values of Contacts(AllContacts) to itemSource of collectionView which populates data to collectionView in Data Template we developed.
  • I have used Style to provide the properties for Label,Image, StackLayout and Frame for better understanding
  • To use Style we need to use ResourceDictionary to provide particular UI Elements property and then use them in Style.

The Below code will have all the design properties I have setted in the Xaml code:

ResourceDictionary — Design Properties of Custom Data Template

4) Working with Selection of collection view cells

As I mentioned above, By default, CollectionView selection is disabled. However, this behavior can be changed by setting the SelectionMode property value to one of the SelectionMode enumeration members:

  • None – indicates that items cannot be selected. This is the default value.
  • Single – indicates that a single item can be selected, with the selected item being highlighted.
  • Multiple – indicates that multiple items can be selected, with the selected items being highlighted.

Xaml

<CollectionView x:Name="collectionViewListHorizontal" HeightRequest="200" SelectionMode="Single"
SelectionChanged="CollectionViewListSelectionChanged">
</CollectionView>
  • SelectedItem, of type object, the selected item in the list. This property has a default binding mode of TwoWay, and has a null value when no item is selected.
  • SelectionChangedCommand, of type ICommand, which is executed when the selected item changes.
  • SelectionChangedCommandParameter, of type object, which is the parameter that's passed to the SelectionChangedCommand.
  • CollectionView defines a SelectionChanged event that is fired when the SelectedItem property changes, either due to the user selecting an item from the list, or when an application sets the property.
  • In addition, this event is also fired when the SelectedItems property changes. The SelectionChangedEventArgs object that accompanies the SelectionChanged event has two properties, both of type IReadOnlyList<object>:
  • PreviousSelection – the list of items that were selected, before the selection changed.
  • CurrentSelection – the list of items that are selected, after the selection change.

Xaml.cs

  void CollectionViewListSelectionChanged(object sender,   SelectionChangedEventArgs e)
{
UpdateSelectionData(e.PreviousSelection, e.CurrentSelection);
}
void UpdateSelectionData(IEnumerable<object> previousSelectedContact, IEnumerable<object> currentSelectedContact)
{
var selectedContact = currentSelectedContact.FirstOrDefault() as Contact;
Debug.WriteLine("FullName: " + selectedContact.FullName);
Debug.WriteLine("Email: " + selectedContact.Email);
Debug.WriteLine("Phone: " + selectedContact.Phone);
Debug.WriteLine("Country: " + selectedContact.Country);
}
  • When the cells in collectionView is selected, SelectionChangedEventArgs will call the CollectionViewListSelectionChanged() where both PreviousSelection and CurrentSelection is enabled.
  • CollectionViewListSelectionChanged() function will call updateSelectionData() function and print the details of contact in Application Output.

Below image shows the output of the selected contact:

Details of Selected CollectionView Cell

5) Working with Horizontal and Vertical Scrolling

  • In collectionView , we can customize scrolling as much as we like but in this example I have used LinearItemsLayout to scroll collectionView Items Horizontal and vertical.
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Horizontal" />
</CollectionView.ItemsLayout>

For More Customized Scrolling Options checkout this link Xamarin.Forms CollectionView Scrolling

6) Conclusion:

Now you know how to work with CollectionView in Xamarin Forms.Find the code and material for this article in Github link.You can refer it incase you have any queries.

If you run the project which I have mentioned in above github link , you will get screen as below:

CollectionView Example Project Output Screens

I hope you found this article helpful. If you did, please don’t hesitate to clap or share this post on Twitter or your social media of choice, every share helps me to write more. If you have any queries, feel free to comment below and I’ll see what I can do.Thanks.

Let’s connect!

You can find me on Twitter | LinkedIn | GitHub

--

--

Shankar Madeshvaran
Developer in Making

iOS and Web/React Js Developer. I write articles regarding Web, iOS ,React.Js concepts. Subscribe for more: https://shankarmadeshvaran.hashnode.dev