List firing Event on Change

前端 未结 5 683
说谎
说谎 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:54

    ObservableCollection is a List with a CollectionChanged event

    ObservableCollection.CollectionChanged Event

    For how to wire up the event handler see answer from Patrick. +1

    Not sure what you are looking for but I use this for a collection with one event that fires on add, remove, and change.

    public class ObservableCollection: INotifyPropertyChanged
    {
        private BindingList ts = new BindingList();
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        // This method is called by the Set accessor of each property. 
        // The CallerMemberName attribute that is applied to the optional propertyName 
        // parameter causes the property name of the caller to be substituted as an argument. 
        private void NotifyPropertyChanged( String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        public BindingList Ts
        {
            get { return ts; }
            set
            {
                if (value != ts)
                {
                    Ts = value;
                    if (Ts != null)
                    {
                        ts.ListChanged += delegate(object sender, ListChangedEventArgs args)
                        {
                            OnListChanged(this);
                        };
                    }
                    NotifyPropertyChanged("Ts");
                }
            }
        }
    
        private static void OnListChanged(ObservableCollection vm)
        {
            // this will fire on add, remove, and change
            // if want to prevent an insert this in not the right spot for that 
            // the OPs use of word prevent is not clear 
            // -1 don't be a hater
            vm.NotifyPropertyChanged("Ts");
        }
    
        public ObservableCollection()
        {
            ts.ListChanged += delegate(object sender, ListChangedEventArgs args)
            {
                OnListChanged(this);
            };
        }
    }
    

提交回复
热议问题