c# – 如何调整ObservableCollection的大小?

前端之家收集整理的这篇文章主要介绍了c# – 如何调整ObservableCollection的大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以调整Observable Collection的大小,或者限制收集项的最大数量?我有一个ObservableCollection作为View Model中的属性(使用MVVM模式).

视图绑定到集合,我试图通过提供在CollectionChanged事件发生时执行的事件处理程序来破解解决方案.在事件处理程序中,我根据需要从集合顶部删除了尽可能多的项目来修剪集合.

  1. ObservableCollection<string> items = new ObservableCollection<string>();
  2. items.CollectionChanged += new NotifyCollectionChangedEventHandler(Items_Changed);
  3.  
  4. void Items_Changed(object sender,NotifyCollectionChangedEventArgs e)
  5. {
  6. if(items.Count > 10)
  7. {
  8. int trimCount = items.Count - 10;
  9. for(int i = 0; i < trimCount; i++)
  10. {
  11. items.Remove(items[0]);
  12. }
  13. }
  14. }

此事件处理程序产生InvalidOperationException,因为它不喜欢我在CollectionChanged事件期间更改集合的事实.我该怎么做才能保持我的收藏大小合适?

解:
Simon Mourier问我是否可以创建一个派生自ObservableCollection的新集合< T>并重写InsertItem(),这就是我所做的具有自动调整大小的ObservableCollection类型.

  1. public class MyCollection<T> : ObservableCollection<T>
  2. {
  3. public int MaxCollectionSize { get; set; }
  4.  
  5. public MyCollection(int maxCollectionSize = 0) : base()
  6. {
  7. MaxCollectionSize = maxCollectionsize;
  8. }
  9.  
  10. protected override void InsertItem(int index,T item)
  11. {
  12. base.InsertItem(index,item);
  13.  
  14. if(MaxCollectionSize > 0 && MaxCollectionSize < Count)
  15. {
  16. int trimCount = Count - MaxCollectionSize;
  17. for(int i=0; i<trimCount; i++)
  18. {
  19. RemoveAt(0);
  20. }
  21. }
  22. }
  23. }

解决方法

你可以派生ObservableCollection类并重写InsertItem方法吗?

猜你在找的C#相关文章