Controls > CollectionView > Features > Incremental Loading |
Incremental loading (on demand loading) is a powerful feature for any mobile application. CollectionView supports incremental loading for data bound controls, such as FlexGrid, ListView. To apply incremental loading on your Xamarin.Forms application, first you need to implement collection view class, which extends a cursor CollectionView and overrides GetPageAsync. Once you have implemented this, you need to add the logic that loads the data in pages or chunks. You can also set the number of pages to be loaded at a time.
The image below shows how the ListBox appears when incremental loading is applied on it.
The following code example demonstrates how to implement on demand loading for a simple ListView control using CollectionView.
<ContentPage></ContentPage>
as shown below.
XAML |
Copy Code |
---|---|
<ListView x:Name="list"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding ItemName}" Detail="{Binding ItemDateTime, StringFormat='Created: {0}'}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> |
IncrementalLoading.xaml
node and open IncrementalLoading
.xaml.cs
to open the C# code behind.
C# |
Copy Code |
---|---|
public partial class SimpleOnDemand : ContentPage { public SimpleOnDemand() { InitializeComponent(); Title = AppResources.SimpleOnDemandTitle; // instantiate our on demand collection view var myCollectionView = new SimpleOnDemandCollectionView(); list.ItemsSource = myCollectionView; // start on demand loading list.LoadItemsOnDemand(myCollectionView); } } public class SimpleOnDemandCollectionView : C1CursorCollectionView<MyDataItem> { public SimpleOnDemandCollectionView() { PageSize = 10; } public int PageSize { get; set; } protected override async Task<Tuple<string, IReadOnlyList<MyDataItem>>> GetPageAsync(string pageToken, int? count = null) { // create new page of items var newItems = new List<MyDataItem>(); for (int i = 0; i < this.PageSize; i++) { newItems.Add(new MyDataItem(this.Count + i)); } return new Tuple<string, IReadOnlyList<MyDataItem>>("token not used", newItems); } } public class MyDataItem { public MyDataItem(int index) { this.ItemName = "My Data Item #" + index.ToString(); this.ItemDateTime = DateTime.Now; } public string ItemName { get; set; } public DateTime ItemDateTime { get; set; } } |