Reputation: 1907
I've implemented ISupportIncrementalLoading to load a lot of items in a list as the user scrolls. When I load the view, its empty and it will only load more data until I scroll the list.
This is the class that implements it
public class DeviceListDataSource<T> : ObservableCollection<T>, ISupportIncrementalLoading
where T : class
{
public int LastItem = 0;
public bool HasMoreItems => hasMoreItems;
private int currentPage;
private List<T> source;
private bool hasMoreItems;
public DeviceListDataSource(List<T> source)
{
this.source = source;
hasMoreItems = true;
}
public async Task<IEnumerable<T>> GetPagedItems(int pageIndex, int pageSize)
{
return await Task.Run(() =>
{
var result = (from p in source
select p).Skip(pageIndex * pageSize).Take(pageSize);
return result;
});
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
var dispatcher = Window.Current.Dispatcher;
return Task.Run(
async () =>
{
var result = await GetPagedItems(currentPage++, (int) count);
if (result == null || result.Count() == 0)
{
hasMoreItems = false;
}
else
{
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() =>
{
foreach (T item in result)
{
Add(item);
}
});
}
return new LoadMoreItemsResult() { Count = (uint)currentPage };
}).AsAsyncOperation();
}
}
}
And in the view model, I assign it to the variable that is bound to the list view in the xaml view: Items = new DeviceListDataSource<DataObject>(source);
Is there a way to load the first X items in the list? Its always 0 when it first loads and it remains that way until I scroll. Many thanks!
Upvotes: 1
Views: 163
Reputation: 10627
Is there a way to load the first X items in the list?
You already had LoadMoreItemsAsync
method implemented in the DeviceListDataSource
class, just invoke this method to manually loading X items code behind when initial loading. For example:
DeviceListDataSource<Data> Items = new DeviceListDataSource<Data>(source);
Items.LoadMoreItemsAsync(10);
Upvotes: 2