I'm trying to create a listview that loads items, then loads more items when you scroll to the bottom of the list.
I have all the code already for retrieving my data using paging.
I just can't seem to find an event for hitting the bottom of a listview.
I'm looking for an MVVM solution for this that works across android and iOS. Is there such a thing?
Try this:
public class LazyLoadingListView : ListView { public static readonly BindableProperty LoadMoreCommandProperty = BindableProperty.Create<LazyLoadingListView, ICommand>(bp => bp.LoadMoreCommand, default(ICommand)); public ICommand LoadMoreCommand { get { return (ICommand)GetValue(LoadMoreCommandProperty); } set { SetValue(LoadMoreCommandProperty, value); } } public LazyLoadingListView() { RegisterLayzyLoading(); } public LazyLoadingListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy) { RegisterLayzyLoading(); } void RegisterLayzyLoading() { ItemAppearing += InfiniteListView_ItemAppearing; } object lastItem; void InfiniteListView_ItemAppearing(object sender, ItemVisibilityEventArgs e) { // if last item is in view: load more items if (ItemsSource is IList items && e.Item == items[items.Count - 1]) { if (e.Item != lastItem && LoadMoreCommand != null && LoadMoreCommand.CanExecute(null)) { lastItem = e.Item; LoadMoreCommand.Execute(null); } } } }
Then in your Xaml bind the LoadMoreCommand to your ViewModel like this
<controls:LazyLoadingListView ItemsSource="{Binding MyItems}" LoadMoreCommand="{Binding LoadMoreItemsCommand}"...
Additionally you can add a loader in the footer while loading more results like this:
<ListView.Footer> <Grid HeightRequest="30" Margin="10"> <ActivityIndicator IsRunning="{Binding IsLoadingMoreItems}" /> </Grid> </ListView.Footer>
Answers
Try this:
Then in your Xaml bind the LoadMoreCommand to your ViewModel like this
Additionally you can add a loader in the footer while loading more results like this:
I'd like to thank a lot for this good and complete example as I could implement it and get an amazing feeling using the App.