Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process of utilizing IncrementalLoadingCollection from CommunityToolkit to enable Incremental loading in WinUI3 is as follows:

  1. Install the Microsoft.Toolkit.WinUI.Controls NuGet package.

  2. In your XAML code, create a ListView or GridView control and set its ItemsSource property to an instance of the IncrementalLoadingCollection class.

<controls:ListView ItemsSource="{x:Bind MyIncrementalCollection}" />
  1. In your code-behind file, create an instance of the class that implements the IIncrementalSource<t> interface. This is the data source that the IncrementalLoadingCollection will use to load data.
private readonly MyDataSource _dataSource = new MyDataSource();
  1. Create an instance of the IncrementalLoadingCollection class and pass in the data source instance and the page size.
public IncrementalLoadingCollection<MyDataItem, MyDataSource> MyIncrementalCollection { get; } = new IncrementalLoadingCollection<MyDataItem, MyDataSource>(_dataSource, pageSize: 20);
  1. Implement the IIncrementalSource<t> interface in your data source class. This includes the GetPagedItemsAsync method which returns a collection of items for the specified page.
public async Task<IEnumerable<MyDataItem>> GetPagedItemsAsync(int pageIndex, int pageSize)
{
    // Retrieve data from the data source for the specified page
    var data = await _myDataService.GetDataAsync(pageIndex, pageSize);

    // Map the data to MyDataItem objects
    var items = data.Select(d => new MyDataItem { Name = d.Name, Value = d.Value });

    return items;
}
  1. Customize the ListView or GridView control by adding columns or customizing the item template.
<controls:GridView ItemsSource="{x:Bind MyIncrementalCollection}">
    <controls:GridView.Columns>
        <controls:GridViewColumn Header="Name" Width="Auto" DisplayMemberBinding="{Binding Name}" />
        <controls:GridViewColumn Header="Value" Width="Auto" DisplayMemberBinding="{Binding Value}" />
    </controls:GridView.Columns>
</controls:GridView>
  1. Run the application to see the incremental loading in action as you scroll through the list. The IncrementalLoadingCollection will use the GetPagedItemsAsync method to load items as needed, asynchronously.