Virtual ObservableCollection

Virtualised collection views like ListView or CarouselView are great as they generate their views on the fly based on a DataTemplate. The problem is they need a collection that contains all elements that you want to display. Sometimes this is not feasible because the collection would be too big or it would take too long to load it completely from a remote location.

After some research I found out that the ItemViews as minimum need  an object that implements IReadOnlyList<T>, INotifyCollectionChanged as Itemsource and even there they only use the [int index] and Count property. So I came up with this handy class:

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;

namespace Helpers{
    public abstract class VirtualObservableCollection<T> : IReadOnlyList<T>, INotifyCollectionChanged
    {
        public IEnumerator<T> GetEnumerator()
        {
            throw new System.NotImplementedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count {
            get { return ItemCountRequest(); }
        }

        public T this[int index]
        {
            get { Debug.WriteLine("Index: {0}",index);
                 return OnDataRequest(index);
            }
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;


        public void SignalCollectionChanged()
        {
            CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        protected abstract  T OnDataRequest(int index);
        protected abstract int ItemCountRequest();


    }
}

You only have to derive your own class from it and override OnDataRequest and ItemCountRequest. OnDataRequest has to return the item that should be displayed for a given index. ItemCountRequest must return the maximum number of items that will be displayed.

 

Contact me:

Leave a Reply

Your email address will not be published. Required fields are marked *