Jef*_*Fay 6 c# collections event-handling observablecollection
是否可以调整Observable Collection的大小,或者限制收集项的最大数量?我有一个ObservableCollection作为View Model中的属性(使用MVVM模式).
视图绑定到集合,我试图通过提供在CollectionChanged事件发生时执行的事件处理程序来破解解决方案.在事件处理程序中,我根据需要从集合顶部删除了尽可能多的项目来修剪集合.
ObservableCollection<string> items = new ObservableCollection<string>();
items.CollectionChanged += new NotifyCollectionChangedEventHandler(Items_Changed);
void Items_Changed(object sender, NotifyCollectionChangedEventArgs e)
{
if(items.Count > 10)
{
int trimCount = items.Count - 10;
for(int i = 0; i < trimCount; i++)
{
items.Remove(items[0]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
此事件处理程序产生一个InvalidOperationException因为它不喜欢我在CollectionChanged事件期间更改集合的事实.我该怎么做才能保持我的收藏大小合适?
解决方案:
Simon Mourier询问我是否可以创建一个派生ObservableCollection<T>和覆盖的新集合InsertItem(),这就是我所做的具有自动调整大小的ObservableCollection类型的集合.
public class MyCollection<T> : ObservableCollection<T>
{
public int MaxCollectionSize { get; set; }
public MyCollection(int maxCollectionSize = 0) : base()
{
MaxCollectionSize = maxCollectionsize;
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
if(MaxCollectionSize > 0 && MaxCollectionSize < Count)
{
int trimCount = Count - MaxCollectionSize;
for(int i=0; i<trimCount; i++)
{
RemoveAt(0);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
public class FixedSizeObservableCollection<T> : ObservableCollection<T>
{
private readonly int maxSize;
public FixedSizeObservableCollection(int maxSize)
{
this.maxSize = maxSize;
}
protected override void InsertItem(int index, T item)
{
if (Count == maxSize)
return; // or throw exception
base.InsertItem(index, item);
}
}
Run Code Online (Sandbox Code Playgroud)