Xamarin Forms Carousel view is throwing index out of range error on subsequent loads

Viewed 380

I have a <CarouselView /> wrapped in a <RefreshView />:

<RefreshView x:DataType="local:CarouselViewModel" Command="{Binding LoadItemsCommand}" IsRefreshing="{Binding IsBusy, Mode=TwoWay}">
  <CarouselView x:Name="MyCarousel"
                ItemsSource="{Binding Items}"
                ItemTemplate="{StaticResource carouselDataTemplateSelector}">
  </CarouselView>
</RefreshView>

When it first loads, no problem. If I navigate away and then back to this view, I get:

[RecyclerView] Cannot scroll to position a LayoutManager set. Call setLayoutManager with a non-null argument.
**System.ArgumentOutOfRangeException:** 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

The view model is quite simple, and I would expect the "IsRefreshing" prop to resolve any indexing issues. It seems apparent that modifying the collection (i.e. web request to see if anything is new) is causing the error? Here's the view model:

public class CarouselViewModel: BaseViewModel
    {
        public Services.ICarouselService DataStore => DependencyService.Get<Services.ICarouselService>();
        
        public ObservableCollection<Item> Items { get; set; }
        public Command LoadItemsCommand { get; }

        public CarouselViewModel()
        {
            Items = new ObservableCollection<Item>();
            LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());        
        }

        
        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Items.Clear();
                var items = await DataStore.ListAsync(true);

                foreach (var item in items)
                {
                    Items.Add(item);
                }
                
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }

        public void OnAppearing()
        {
            IsBusy = true;
        }
        
    }

I've included the error right before it is thrown related to the recycler view as this may have something to do with it. It seems that the carousel is not actually refreshing. Should the isBusy flag be preventing this?

0 Answers
Related