Issue
I want to add items in CollectionView
automatically while scrolling in Xamarin Forms. I have an ObservableCollection<ModelItem>
object as an ItemsSource
to CollectionView
. how can I update ItemsSource while scrolling so that items in CollectionView
also get added.
Solution
Use CollectionView
‘s RemainingItemsThreshold
and RemainingItemsThresholdReached
properties for adding items incrementally to the CollectionView
.
RemainingItemsThreshold
is used to fire RemainingItemsThresholdReached
event whenever specific number of items are remaining to be scrolled in the collection.
Also use RefreshView
to show refreshing animation while items are added incrementally.
Here is the XAML code
<RefreshView x:Name"refreshView">
<CollectionView x:Name"collectionView" RemainingItemsThreshold"5"
RemainingItemsThresholdReached"LoadItemsIncrementally"
Margin"10" VerticalScrollBarVisibility"Always">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Margin"5">
<Label Text"{Binding ItemName}" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</RefreshView>
Here is the C# Code
bool isLoading;
public void LoadItemsFirstTimeInCollectionView()
{
Items new ObservableCollection<CompanyItem>();
collectionView.ItemsSource Items; // You can use Binding as an ItemsSource in XAML
refreshView.IsRefreshing true;
for (int i 0; i < 20; i++)
Items.Add(YourListOrCollection[i]);
refreshView.IsRefreshing false;
}
public void LoadItemsIncrementally(object sender, EventArgs e)
{
if (isLoading || Items.Count 0)
return;
isLoading true;
int LastItemIndex Items.Count;
refreshView.IsRefreshing true;
Device.StartTimer(TimeSpan.FromSeconds(2), () > // Fake 2 seconds, Modify with your API call or anything else
{
for (int i LastItemIndex; i < LastItemIndex + 20; i++)
Items.Add(YourListOrCollection[i]);
isLoading false;
refreshView.IsRefreshing false;
return false;
});
}
Refer here for official documentation
Answered By – Juned Khan Momin