Infinite Scrolling ListView For Xamarin.Forms App Using Behaviors

Behaviors is one of the extremely useful features in Xamarin.Forms that allows the user to add a new functionality in an already existing element in the view. Programmers just have to create a class that inherits from Behavior<T> where ‘T’ is an Element which is being extended. ListView is a control to store list of objects whose source might be static data from the web. But once in a while programmers need to get limited data time as a user scrolls (For example for news, a user might need to get 10 pieces of news at a time as news in the server may be in the thousands in number causing the app to crash). As Infinite scrolling is not a feature in ListView we have to insert a piece of code to get this functionality.

Create a new Xamarin.Forms App and select PCL(Portable Class Library),

Create a Folder named “Behaviors” and add a class InfiniteScroll inside it,

Inherit the class Behavior<ListView> which lies in namespace Xamarin.Forms and add the following codes,

The above code will create a ‘LoadMoreCommandProperty’ which is a type of command and will be invoked when the last item of list is diaplayed. We use OnAttachedTo and OnDetachingFrom methods to bind our context and invoke the command when ListView ItemAppearing event is triggered on last Item. Now that our bindable property is complete we need to create a listview in MainPage to get the functionality working.

But before that add a repository class which will return data page wise,

publicclass NewsRepository {

public List < string > News {

get;

set;

}

public NewsRepository() {

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("2");

News.Add("2");

News.Add("3");

News.Add("4");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

News.Add("1");

}

public List < string > getNews(int page) {

return News.Take(10).Skip(page - 1).ToList();

}

}

As we are using MVVM pattern we will create a new ViewModel which will contain a command and a List which contains the items of ListView. For this create a folder ViewModel and add class NewsViewModel. NewsViewModel will get data from the repository and notify when new data is loaded to listview.