.NET MAUI CollectionView LoadOnDemand Command
The LoadOnDemandCommand
(of type ICommand
) is another alternative which you can use for loading data on demand. This alternative is suitable for MVVM scenarios.
Example
The following example demonstrates a simple setup that shows how to use the command:
1. Create a sample model:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
2. Define the CollectionView control:
<telerik:RadCollectionView ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
IsLoadOnDemandEnabled="True"
IsLoadOnDemandActive="{Binding IsLoadOnDemandActive, Mode=TwoWay}"
LoadOnDemandCommand="{Binding LoadOnDemandCommand}">
<telerik:RadCollectionView.BindingContext>
<local:LoadOnDemandCommandViewModel />
</telerik:RadCollectionView.BindingContext>
</telerik:RadCollectionView>
3. Add the telerik
namespace:
xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
4. Create a ViewModel
and define a command that is bound to the RadCollectionView.LoadOnDemandCommand
property:
public class LoadOnDemandCommandViewModel : NotifyPropertyChangedBase
{
private bool isLoadOnDemandActive;
public LoadOnDemandCommandViewModel()
{
this.Items = new ObservableCollection<Person>();
for (int i = 0; i < 20; i++)
{
this.Items.Add(new Person { Name = "Person " + i, Age = i + 10 });
}
this.LoadOnDemandCommand = new Command(async () =>
{
this.IsLoadOnDemandActive = true;
IEnumerable<Person> newItems = await this.GetNewItems();
foreach (var newItem in newItems)
{
this.Items.Add(newItem);
}
this.IsLoadOnDemandActive = false;
});
}
public ObservableCollection<Person> Items { get; set; }
public ICommand LoadOnDemandCommand { get; set; }
public bool IsLoadOnDemandActive
{
get => this.isLoadOnDemandActive;
set => this.UpdateValue(ref this.isLoadOnDemandActive, value);
}
private async Task<IEnumerable<Person>> GetNewItems()
{
List<Person> newItems = new List<Person>();
int count = this.Items.Count;
try
{
await Task.Delay(2000);
for (int i = 0; i < 10; i++)
{
newItems.Add(new Person { Name = $"Loaded item: Person {count + i}", Age = i + 10 });
}
return newItems;
}
catch (Exception)
{
return null;
}
}
}
This is the result:
For a runnable example demonstrating the CollectionView LoadOnDemand Command, see the SDKBrowser Demo Application and go to CollectionView > Load On Demand category.