1

I am trying to implement a collection view that allows limiting the amount of filtered out items.

I have come up with this implementation

public class LimitCollectionView : ListCollectionView
{
    #region CONSTRUCTOR
    public LimitCollectionView(IList source) : base(source)
    {          
    }
    #endregion

    #region FIELDS
    private int MAX_ITEMS = 0;
    #endregion

    #region PROPERTIES

    /// <summary>
    /// Gets or sets maximum amount of view items.
    /// </summary>
    public int MaxItems
    {
        get { return MAX_ITEMS; }
        set
        {
            MAX_ITEMS = value;
            OnPropertyChanged(new ComponentModel.PropertyChangedEventArgs(nameof(MaxItems)));
            RefreshOrDefer();
        }
    }

    #endregion

    #region OVERRIDES       

    /// <summary>
    /// Gets the estimated number of records.
    /// </summary>
    public override int Count
    {
        get
        {
            if (IsRefreshDeferred)
                return 0;

            if (MaxItems <= 0)
                return base.Count;        

            var baseCount = base.Count;

            if (MaxItems > baseCount)
                return baseCount;

            return Math.Min(MaxItems,baseCount);
        }
    }

    public override bool PassesFilter(object item)
    {
        if (!base.PassesFilter(item))
            return false;

        if(item!=null)
        {
            return IndexOf(item) < MaxItems;
        }

        return true;
    }

    #endregion
}

In most cases the implementation works as intended BUT at some cases i get System.InvalidOperationException: An ItemsControl is inconsistent with its items source.

So i suppose there is inconsistency with what ItemsControl expects and what my CollectionView reporting. So the question is have i omitted something in my implementation ? Is it even possible to have an implementation that works ?

I know i could filter out items manually and recreate the collection on change but that beats the the purpose of CollectionView.

NullReference
  • 862
  • 1
  • 11
  • 27
  • "at some cases i get System.InvalidOperationException" -- which cases? – 15ee8f99-57ff-4f92-890c-b56153 Jun 11 '19 at 14:23
  • I think maybe you are changing the collection while reading it, maybe try the suggestion here https://stackoverflow.com/questions/22524569/an-itemscontrol-is-inconsistent-with-its-items-source-wpf-listbox and EnableCollectionSynchronization – yawnobleix Jun 11 '19 at 14:25
  • Is it about virtualization? Why do you think it's a good idea to subclass `ListCollectionView`? – Sinatr Jun 11 '19 at 14:26
  • The collection view has an observable collection as source and sure EnableCollectionSynchronization is used on it so there should be no race conditions. @Sinatr i dont know if its a good idea but its a requirement. – NullReference Jun 11 '19 at 14:37

0 Answers0