Observable Stack and Queue

后端 未结 4 1927
无人及你
无人及你 2020-11-27 22:34

I\'m looking for an INotifyCollectionChanged implementation of Stack and Queue. I could roll my own but I don\'t want to reinvent the

4条回答
  •  盖世英雄少女心
    2020-11-27 22:45

    I run into the same issue and want to share my solution to others. Hope this is helpful to someone.

    public class ObservableStack : Stack, INotifyCollectionChanged, INotifyPropertyChanged
    {
        public ObservableStack()
        {
        }
    
        public ObservableStack(IEnumerable collection)
        {
            foreach (var item in collection)
                base.Push(item);
        }
    
        public ObservableStack(List list)
        {
            foreach (var item in list)
                base.Push(item);
        }
    
    
        public new virtual void Clear()
        {
            base.Clear();
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    
        public new virtual T Pop()
        {
            var item = base.Pop();
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
            return item;
        }
    
        public new virtual void Push(T item)
        {
            base.Push(item);
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
        }
    
    
        public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
    
    
        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            this.RaiseCollectionChanged(e);
        }
    
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            this.RaisePropertyChanged(e);
        }
    
    
        protected virtual event PropertyChangedEventHandler PropertyChanged;
    
    
        private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (this.CollectionChanged != null)
                this.CollectionChanged(this, e);
        }
    
        private void RaisePropertyChanged(PropertyChangedEventArgs e)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, e);
        }
    
    
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add { this.PropertyChanged += value; }
            remove { this.PropertyChanged -= value; }
        }
    }
    

提交回复
热议问题