• Linux
  • Nginx
  • 数据库
  • Python
  • PHP
  • C#
  • .NET
  • WPF
  • MAUI
  • Blazor
  • WinForm
  • 帝国CMS
  • AKCMS
  • Typecho
  • 织梦CMS
  • Visual Studio
  • Windows
  • Mac
  • Web前端
  • 数据采集
  • 运营
  • 产品
  • 摩托车
  • 电影
  • 杂事
  • ObservableCollection继承了INotifyPropertyChanged接口,在属性变更时可以通知界面,当我把ObservableCollection集合绑定到界面的DataGrid后,我希望在界面修改表格数值后,可以触发一个 事件来验证我界面设定数据的有效性,但是对于集合的添加、删除只会触发集合的get属性,值重置不会触发集合的get、set属性,这时候我们就需要扩展ObservableCollection集合. .

    代码如下:重写OnCollectionChanged方法,使得集合改变(增添、删除、改变)时拥有属性变更事件

    using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using DevExpress.Xpo; namespace Caliburn.Micro.Hello public class ItemsChangeObservableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T> where T : INotifyPropertyChanged protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) if (e.Action == NotifyCollectionChangedAction.Add) RegisterPropertyChanged(e.NewItems); else if (e.Action == NotifyCollectionChangedAction.Remove) UnRegisterPropertyChanged(e.OldItems); else if (e.Action == NotifyCollectionChangedAction.Replace) UnRegisterPropertyChanged(e.OldItems); RegisterPropertyChanged(e.NewItems); base.OnCollectionChanged(e); protected override void ClearItems() UnRegisterPropertyChanged(this); base.ClearItems(); private void RegisterPropertyChanged(IList items) foreach (INotifyPropertyChanged item in items) if (item != null) item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged); private void UnRegisterPropertyChanged(IList items) foreach (INotifyPropertyChanged item in items) if (item != null) item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged); private void item_PropertyChanged(object sender, PropertyChangedEventArgs e) //launch an event Reset with name of property changed base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

    可以用如下方法订阅事件:

    this.StudentList.CollectionChanged += StudentList_OnCollectionChanged; StudentList.CollectionChanged += new NotifyCollectionChangedEventHandler(StudentList_OnCollectionChanged);

    事件方法:

    public void StudentList_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) MessageBox.Show("当前触发的事件是:"+ e.Action.ToString());

    集合定义:

    private ItemsChangeObservableCollection<Students> studentList; public ItemsChangeObservableCollection<Students> StudentList return studentList; studentList = value; 本文作者:zls365 信息来源: 公众号 dotNET编程大全 所属分类: C# Power by Typecho. Theme by Puma. Written by 董川民- 独立开发者 渝ICP备16006207号-2 渝公网安备 50011202503233号

    友情链接: