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.