Как добавлять элементы постепенно во время прокрутки в CollectionView в формах Xamarin?

#c# #xaml #xamarin #xamarin.forms

Вопрос:

Я хочу CollectionView автоматически добавлять элементы при прокрутке в формах Xamarin. У меня есть ObservableCollection<ModelItem> объект в качестве ItemsSource «к CollectionView «. как я могу обновить источник элементов при прокрутке, чтобы элементы CollectionView также добавлялись.

Ответ №1:

Используйте CollectionView » s RemainingItemsThreshold и RemainingItemsThresholdReached свойства для постепенного добавления элементов в CollectionView .

RemainingItemsThreshold используется для запуска RemainingItemsThresholdReached события всякий раз, когда определенное количество элементов остается для прокрутки в коллекции.

Также используйте RefreshView для отображения обновляющейся анимации во время постепенного добавления элементов.

Вот код XAML

 <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>
 

Вот код на C#

 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;
    });
}
 

Официальную документацию можно найти здесь