Observable Stack and Queue

后端 未结 4 1898
无人及你
无人及你 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:54

    Very similar to the above class, with a few exceptions:

    1. Publish prop changed for collection changes for Count
    2. Override TrimExcess() b/c that could affect Count
    3. Made events public so I don't have to cast to the interface
    4. Passes index to collectionchanged when appropriate
        public class ObservableStack : Stack, INotifyPropertyChanged, INotifyCollectionChanged
        {
          public ObservableStack(IEnumerable collection) : base(collection) {}
          public ObservableStack() { } 
    
          public event PropertyChangedEventHandler PropertyChanged = delegate { };
          public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };
    
          protected virtual void OnCollectionChanged(NotifyCollectionChangedAction action, List items, int? index = null)
          {
            if (index.HasValue)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, items, index.Value));
            }
            else
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, items));
            }
             OnPropertyChanged(GetPropertyName(() => Count));
          }
    
          protected virtual void OnPropertyChanged(string propName)
          {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
          }
    
          public new virtual void Clear()
          {
            base.Clear();
            OnCollectionChanged(NotifyCollectionChangedAction.Reset, null);
          }
    
          public new virtual T Pop()
          {
            var result = base.Pop();
            OnCollectionChanged(NotifyCollectionChangedAction.Remove, new List() { result }, base.Count);
            return result;
          }
    
          public new virtual void Push(T item)
          {
            base.Push(item);
            OnCollectionChanged(NotifyCollectionChangedAction.Add, new List() { item }, base.Count - 1);
          }   
    
          public new virtual void TrimExcess()
          {
            base.TrimExcess();
            OnPropertyChanged(GetPropertyName(() => Count));
          }
    
    String GetPropertyName(Expression> propertyId)
    {
       return ((MemberExpression)propertyId.Body).Member.Name;
    }
    
        }

提交回复
热议问题