3 回答
TA贡献1827条经验 获得超9个赞
您可以创建自己的大小受限的可观察集合类。这样的事情应该可以帮助您入门:
public class LimitedSizeObservableCollection<T> : INotifyCollectionChanged
{
private ObservableCollection<T> _collection;
private bool _ignoreChange;
public LimitedSizeObservableCollection(int capacity)
{
Capacity = capacity;
_ignoreChange = false;
_collection = new ObservableCollection<T>();
_collection.CollectionChanged += _collection_CollectionChanged;
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public int Capacity {get;}
public void Add(T item)
{
if(_collection.Count = Capacity)
{
_ignoreChange = true;
_collection.RemoveAt(0);
_ignoreChange = false;
}
_collection.Add(item);
}
private void _collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(!_ignoreChange)
{
CollectionChanged?.Invoke(this, e);
}
}
}
当然,您可能必须公开更多方法,但是我希望这足以使您理解。
TA贡献1796条经验 获得超7个赞
可以通过此类轻松完成:
public class LimitedSizeObservableCollection<T> : ObservableCollection<T>
{
public int Capacity { get; }
public LimitedSizeObservableCollection(int capacity)
{
Capacity = capacity;
}
public new void Add(T item)
{
if (Count >= Capacity)
{
this.RemoveAt(0);
}
base.Add(item);
}
}
- 3 回答
- 0 关注
- 551 浏览
添加回答
举报