I\'m looking for an INotifyCollectionChanged implementation of Stack and Queue. I could roll my own but I don\'t want to reinvent the
I realize there are already a few answers but figured I would give back a little with mine. I put together everything mentioned in the posts and comments. There were few things that motivated me to do this:
Count when Push, Pop, or Clear are called, as mentioned in one of the posts.Clear, action should be Reset and index for the collection change event should be set to -1 (which it will default to anyway if not set so the other posts have that): .NET docsPush/Pop, action should be Add/Remove and index for the collection changed event should be 0 for a stack being that it is always and only the first item that can be maniuplated (think stack.GetEnumerator().MoveNext()).Stack and use base() calls since there is no reason to override the logic.Results in:
public class ObservableStack : Stack, INotifyCollectionChanged, INotifyPropertyChanged
{
#region Constructors
public ObservableStack() : base() { }
public ObservableStack(IEnumerable collection) : base(collection) { }
public ObservableStack(int capacity) : base(capacity) { }
#endregion
#region Overrides
public virtual new T Pop()
{
var item = base.Pop();
OnCollectionChanged(NotifyCollectionChangedAction.Remove, item);
return item;
}
public virtual new void Push(T item)
{
base.Push(item);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item);
}
public virtual new void Clear()
{
base.Clear();
OnCollectionChanged(NotifyCollectionChangedAction.Reset, default);
}
#endregion
#region CollectionChanged
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedAction action, T item)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(
action
, item
, item == null ? -1 : 0)
);
OnPropertyChanged(nameof(Count));
}
#endregion
#region PropertyChanged
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string proertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(proertyName));
}
#endregion
}