扩展集合ObservableCollection使集合在添加、删除、值变更后触发事件

概述

ObservableCollection继承了INotifyPropertyChanged接口,在属性变更时可以通知界面,当我把ObservableCollection集合绑定到界面的DataGrid后,我希望在界面修改表格数值后,可以触发一个 事件来验证我界面设定数据的有效性,但是对于集合的添加、删除只会触发集合的get属性,值重置不会触发集合的get、set属性,这时候我们就需要扩展ObservableCollection集合.

集合扩展

  • 代码如下:重写OnCollectionChanged方法,使得集合改变(增添、删除、改变)时拥有属性变更事件
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Specialized;
  4. using System.ComponentModel;
  5. using DevExpress.Xpo;
  6. namespace Caliburn.Micro.Hello
  7. {
  8. public class ItemsChangeObservableCollection<T> :
  9. System.Collections.ObjectModel.ObservableCollection<T> where T : INotifyPropertyChanged
  10. {
  11. protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  12. {
  13. if (e.Action == NotifyCollectionChangedAction.Add)
  14. {
  15. RegisterPropertyChanged(e.NewItems);
  16. }
  17. else if (e.Action == NotifyCollectionChangedAction.Remove)
  18. {
  19. UnRegisterPropertyChanged(e.OldItems);
  20. }
  21. else if (e.Action == NotifyCollectionChangedAction.Replace)
  22. {
  23. UnRegisterPropertyChanged(e.OldItems);
  24. RegisterPropertyChanged(e.NewItems);
  25. }
  26. base.OnCollectionChanged(e);
  27. }
  28. protected override void ClearItems()
  29. {
  30. UnRegisterPropertyChanged(this);
  31. base.ClearItems();
  32. }
  33. private void RegisterPropertyChanged(IList items)
  34. {
  35. foreach (INotifyPropertyChanged item in items)
  36. {
  37. if (item != null)
  38. {
  39. item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
  40. }
  41. }
  42. }
  43. private void UnRegisterPropertyChanged(IList items)
  44. {
  45. foreach (INotifyPropertyChanged item in items)
  46. {
  47. if (item != null)
  48. {
  49. item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
  50. }
  51. }
  52. }
  53. private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
  54. {
  55. //launch an event Reset with name of property changed
  56. base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  57. }
  58. }
  59. }

事件订阅

  • 可以用如下方法订阅事件:
  1. this.StudentList.CollectionChanged += StudentList_OnCollectionChanged;
  2. StudentList.CollectionChanged += new NotifyCollectionChangedEventHandler(StudentList_OnCollectionChanged);
  • 事件方法:
  1. public void StudentList_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  2. {
  3. MessageBox.Show("当前触发的事件是:"+ e.Action.ToString());
  4. }
  • 集合定义:
  1. private ItemsChangeObservableCollection<Students> studentList;
  2. public ItemsChangeObservableCollection<Students> StudentList
  3. {
  4. get
  5. {
  6. return studentList;
  7. }
  8. set
  9. {
  10. studentList = value;
  11. }
  12. }

参考资料