List firing Event on Change

前端 未结 5 671
说谎
说谎 2020-12-10 03:37

I created a Class EventList inheriting List which fires an Event each time something is Added, Inserted or Removed:

public          


        
5条回答
  •  有刺的猬
    2020-12-10 03:45

    If an ObservableCollection is not the solution for you, you can try that:

    A) Implement a custom EventArgs that will contain the new Count attribute when an event will be fired.

    public class ChangeListCountEventArgs : EventArgs
    {
        public int NewCount
        {
            get;
            set;
        }
    
        public ChangeListCountEventArgs(int newCount)
        {
            NewCount = newCount;
        }
    }
    

    B) Implement a custom List that inherits from List and redefine the Count attribute and the constructors according to your needs:

    public class CustomList : List
    {
        public event EventHandler ListCountChanged;
    
        public new int Count
        {
            get
            {
                ListCountChanged?.Invoke(this, new ChangeListCountEventArgs(base.Count));
                return base.Count;
            }
        }
    
        public CustomList()
        { }
    
        public CustomList(List list) : base(list)
        { }
    
        public CustomList(CustomList list) : base(list)
        { }
    }
    

    C) Finally subscribe to your event:

    var myList = new CustomList();
    myList.ListCountChanged += (obj, e) => 
    {
        // get the count thanks to e.NewCount
    };
    

提交回复
热议问题