C# .NET可观测的

C# .NET可观测的,c#,.net,observablecollection,dictionary,C#,.net,Observablecollection,Dictionary,我编写了以下类,该类实现(或尝试!)带有通知的字典: public partial class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged { public ObservableDictionary() : base() { } public ObservableDictionary(int capacity) : base(

我编写了以下类,该类实现(或尝试!)带有通知的字典:

public partial class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged
{
    public ObservableDictionary() : base() { }
    public ObservableDictionary(int capacity) : base(capacity) { }
    public ObservableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
    public ObservableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
    public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }
    public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer) { }

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public new TValue this[TKey key]
    {
        get
        {
            return base[key];
        }
        set
        {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, key, 0));
            base[key] = value;
        }
    }

    public new void Add(TKey key, TValue value)
    {
        base.Add(key, value);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, key, 0));
    }

    public new bool Remove(TKey key)
    {
        bool x = base.Remove(key);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, key, 0));
        return x;
    }

    public new void Clear()
    {
        base.Clear();
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }


    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(this, e);
        }
    }
}
public分部类observedictionary:Dictionary,INotifyCollectionChanged
{
public observedictionary():base(){}
公共观测(国际容量):基本(容量){}
公共observedictionary(IEqualityComparer-comparer-comparer):基(comparer){}
公共词典(IDictionary dictionary):基本词典{}
公共observedictionary(int-capacity,IEqualityComparer-comparer-comparer):基(capacity,comparer){}
公共observedictionary(IDictionary dictionary,IEqualityComparer-comparer-comparer):base(dictionary,comparer){}
公共事件通知CollectionChangedEventHandler CollectionChanged;
公共新TValue此[TKey]
{
得到
{
返回基[键];
}
设置
{
OnCollectionChanged(新的NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace,键,0));
基[键]=值;
}
}
公共新空添加(TKey key,TValue value)
{
添加(键、值);
OnCollectionChanged(新的NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,键,0));
}
公共新bool删除(TKey)
{
bool x=基础。移除(键);
OnCollectionChanged(新建NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,键,0));
返回x;
}
公共新空白清除()
{
base.Clear();
OnCollectionChanged(新建NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
CollectionChanged上受保护的虚拟空间(NotifyCollectionChangedEventArgs e)
{
如果(CollectionChanged!=null)
{
集合更改(本,e);
}
}
}
在另一个类中,我有一个MyObservableDictionary.CollectionChanged事件的侦听器:


我遇到的问题是,活动没有启动。如何解决此问题?

我建议您实现
IDictionary
,而不是从
字典继承。由于您必须使用
new
而不是
override
,因此可能只是在基类上而不是在您的类上调用这些方法。我很想在内部使用
字典
来实际存储数据

事实上,我发现:

我设法找到了一个解决方案-变通办法

public delegate void CollectionAlteredEventHander( object sender , EventArgs e);

public partial class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{

    /*Class contructors*/

    public event CollectionAlteredEventHander CollectionAltered;

    public new TValue this[TKey key]
    {
        get
        {
            return base[key];
        }
        set
        {
            OnCollectionAltered(new EventArgs());
            base[key] = value;
        }
    }

    public new void Add(TKey key, TValue value)
    {
        int idx = 0;
        if (!TryGetKeyIndex(this, key, ref idx))
        {
            base.Add(key, value);
            OnCollectionAltered(new EventArgs());
        }
    }

    public new bool Remove(TKey key)
    {
        int idx = 0; 
        if( TryGetKeyIndex( this ,key, ref idx))
        {
            OnCollectionAltered(new EventArgs());
            return base.Remove(key);
        }
        return false;
    }

    private bool TryGetKeyIndex(ObservableDictionary<TKey, TValue> observableDictionary, TKey key , ref int idx)
    {
        foreach (KeyValuePair<TKey, TValue> pair in observableDictionary) 
        {
            if (pair.Key.Equals(key)) 
            {
                return true;
            }
            idx++;
        }
        return false;
    }

    public new void Clear()
    {
        OnCollectionAltered(new EventArgs());
        base.Clear();            
    }

    protected virtual void OnCollectionAltered(EventArgs e)
    {
        if (CollectionAltered != null)
        {
            CollectionAltered(this, e);
        }
    }

}
public委托void collectionateredventhander(对象发送方,事件参数e);
公共部分类Observiceary:字典
{
/*类构造函数*/
公共活动集体化;
公共新TValue此[TKey]
{
得到
{
返回基[键];
}
设置
{
OnCollectionChanged(新的EventArgs());
基[键]=值;
}
}
公共新空添加(TKey key,TValue value)
{
int-idx=0;
if(!TryGetKeyIndex(this,key,ref idx))
{
添加(键、值);
OnCollectionChanged(新的EventArgs());
}
}
公共新bool删除(TKey)
{
int-idx=0;
if(TryGetKeyIndex(this,key,ref idx))
{
OnCollectionChanged(新的EventArgs());
返回底座。移除(键);
}
返回false;
}
私有bool-TryGetKeyIndex(observedictionary-observedictionary,TKey-key,ref-int-idx)
{
foreach(ObserverDictionary中的KeyValuePair对)
{
if(pair.Key.Equals(Key))
{
返回true;
}
idx++;
}
返回false;
}
公共新空白清除()
{
OnCollectionChanged(新的EventArgs());
base.Clear();
}
CollectionChanged上受保护的虚拟空间(EventArgs e)
{
if(collectionartered!=null)
{
集合的(本,e);
}
}
}
不过,我不再实现
INotifyCollectionChanged
接口

您的解决方案-已修复;)

public类observedictionary:Dictionary、INotifyCollectionChanged、INotifyPropertyChanged{
public observedictionary():base(){}
公共观测(国际容量):基本(容量){}
公共observedictionary(IEqualityComparer-comparer-comparer):基(comparer){}
公共词典(IDictionary dictionary):基本词典{}
公共observedictionary(int-capacity,IEqualityComparer-comparer-comparer):基(capacity,comparer){}
公共observedictionary(IDictionary dictionary,IEqualityComparer-comparer-comparer):base(dictionary,comparer){}
公共事件通知CollectionChangedEventHandler CollectionChanged;
公共事件属性更改事件处理程序属性更改;
公共新TValue此[TKey]{
得到{
返回基[键];
}
设置{
TValue oldValue;
bool exist=base.TryGetValue(key,out oldValue);
var oldItem=新的KeyValuePair(键,oldValue);
基[键]=值;
var newItem=新的KeyValuePair(键,值);
如果(存在){
this.OnCollectionChanged(新的NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace、newItem、oldItem、base.Keys.ToList().IndexOf(key));
}否则{
this.OnCollectionChanged(新的notifyCollectionChangedEntargs(NotifyCollectionChangedAction.Add,newItem,base.Keys.ToList().IndexOf(key));
this.OnPropertyChanged(新PropertyChangedEventArgs(name of(Count));
}
}
}
公共新空添加(TKey key,TValue value){
如果(!base.ContainsKey(键)){
var项=新的KeyValuePair(键,值);
添加(键、值);
这是陈学院
public class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged {
    public ObservableDictionary( ) : base( ) { }
    public ObservableDictionary(int capacity) : base(capacity) { }
    public ObservableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
    public ObservableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
    public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }
    public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer) { }

    public event NotifyCollectionChangedEventHandler CollectionChanged;
    public event PropertyChangedEventHandler PropertyChanged;

    public new TValue this[TKey key] {
        get {
            return base[key];
        }
        set {
            TValue oldValue;
            bool exist = base.TryGetValue(key, out oldValue);
            var oldItem = new KeyValuePair<TKey, TValue>(key, oldValue);
            base[key] = value;
            var newItem = new KeyValuePair<TKey, TValue>(key, value);
            if (exist) {
                this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, base.Keys.ToList( ).IndexOf(key)));
            } else {
                this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItem, base.Keys.ToList( ).IndexOf(key)));
                this.OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
            }
        }
    }

    public new void Add(TKey key, TValue value) {
        if (!base.ContainsKey(key)) {
            var item = new KeyValuePair<TKey, TValue>(key, value);
            base.Add(key, value);
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, base.Keys.ToList( ).IndexOf(key)));
            this.OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
        }
    }

    public new bool Remove(TKey key) {
        TValue value;
        if (base.TryGetValue(key, out value)) {
            var item = new KeyValuePair<TKey, TValue>(key, base[key]);
            bool result = base.Remove(key);
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, base.Keys.ToList( ).IndexOf(key)));
            this.OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
            return result;
        }
        return false;
    }

    public new void Clear( ) {
        base.Clear( );
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        this.OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
    }

    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) {
        if (this.CollectionChanged != null) {
            this.CollectionChanged(this, e);
        }
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        if (this.PropertyChanged != null) {
            this.PropertyChanged(this, e);
        }
    }
}
//--------------------------------------------------------------------------
// 
//  Copyright (c) Microsoft Corporation.  All rights reserved. 
// 
//  File: ObservableConcurrentDictionary.cs
//
//--------------------------------------------------------------------------

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;

namespace System.Collections.Concurrent
{
    /// <summary>
    /// Provides a thread-safe dictionary for use with data binding.
    /// </summary>
    /// <typeparam name="TKey">Specifies the type of the keys in this collection.</typeparam>
    /// <typeparam name="TValue">Specifies the type of the values in this collection.</typeparam>
    [DebuggerDisplay("Count={Count}")]
    public class ObservableConcurrentDictionary<TKey, TValue> :
        ICollection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>,
        INotifyCollectionChanged, INotifyPropertyChanged
    {
        private readonly SynchronizationContext _context;
        private readonly ConcurrentDictionary<TKey, TValue> _dictionary;

        /// <summary>
        /// Initializes an instance of the ObservableConcurrentDictionary class.
        /// </summary>
        public ObservableConcurrentDictionary()
        {
            _context = AsyncOperationManager.SynchronizationContext;
            _dictionary = new ConcurrentDictionary<TKey, TValue>();
        }

        /// <summary>Event raised when the collection changes.</summary>
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        /// <summary>Event raised when a property on the collection changes.</summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
        /// </summary>
        private void NotifyObserversOfChange()
        {
            var collectionHandler = CollectionChanged;
            var propertyHandler = PropertyChanged;
            if (collectionHandler != null || propertyHandler != null)
            {
                _context.Post(s =>
                {
                    if (collectionHandler != null)
                    {
                        collectionHandler(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    }
                    if (propertyHandler != null)
                    {
                        propertyHandler(this, new PropertyChangedEventArgs("Count"));
                        propertyHandler(this, new PropertyChangedEventArgs("Keys"));
                        propertyHandler(this, new PropertyChangedEventArgs("Values"));
                    }
                }, null);
            }
        }

        /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
        /// <param name="item">The item to be added.</param>
        /// <returns>Whether the add was successful.</returns>
        private bool TryAddWithNotification(KeyValuePair<TKey, TValue> item)
        {
            return TryAddWithNotification(item.Key, item.Value);
        }

        /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be added.</param>
        /// <param name="value">The value of the item to be added.</param>
        /// <returns>Whether the add was successful.</returns>
        private bool TryAddWithNotification(TKey key, TValue value)
        {
            bool result = _dictionary.TryAdd(key, value);
            if (result) NotifyObserversOfChange();
            return result;
        }

        /// <summary>Attempts to remove an item from the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be removed.</param>
        /// <param name="value">The value of the item removed.</param>
        /// <returns>Whether the removal was successful.</returns>
        private bool TryRemoveWithNotification(TKey key, out TValue value)
        {
            bool result = _dictionary.TryRemove(key, out value);
            if (result) NotifyObserversOfChange();
            return result;
        }

        /// <summary>Attempts to add or update an item in the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be updated.</param>
        /// <param name="value">The new value to set for the item.</param>
        /// <returns>Whether the update was successful.</returns>
        private void UpdateWithNotification(TKey key, TValue value)
        {
            _dictionary[key] = value;
            NotifyObserversOfChange();
        }

        #region ICollection<KeyValuePair<TKey,TValue>> Members
        void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
        {
            TryAddWithNotification(item);
        }

        void ICollection<KeyValuePair<TKey, TValue>>.Clear()
        {
            ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Clear();
            NotifyObserversOfChange();
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
        {
            return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Contains(item);
        }

        void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);
        }

        int ICollection<KeyValuePair<TKey, TValue>>.Count
        {
            get { return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Count; }
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
        {
            get { return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).IsReadOnly; }
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
        {
            TValue temp;
            return TryRemoveWithNotification(item.Key, out temp);
        }
        #endregion

        #region IEnumerable<KeyValuePair<TKey,TValue>> Members
        IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
        {
            return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
        }
        #endregion

        #region IDictionary<TKey,TValue> Members
        public void Add(TKey key, TValue value)
        {
            TryAddWithNotification(key, value);
        }

        public bool ContainsKey(TKey key)
        {
            return _dictionary.ContainsKey(key);
        }

        public ICollection<TKey> Keys
        {
            get { return _dictionary.Keys; }
        }

        public bool Remove(TKey key)
        {
            TValue temp;
            return TryRemoveWithNotification(key, out temp);
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            return _dictionary.TryGetValue(key, out value);
        }

        public ICollection<TValue> Values
        {
            get { return _dictionary.Values; }
        }

        public TValue this[TKey key]
        {
            get { return _dictionary[key]; }
            set { UpdateWithNotification(key, value); }
        }
        #endregion
    }
}
//--------------------------------------------------------------------------
// 
//  Copyright (c) Microsoft Corporation.  All rights reserved. 
// 
//  File: ObservableConcurrentDictionary.cs
//
//--------------------------------------------------------------------------

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;

namespace System.Collections.Concurrent
{
    /// <summary>
    /// Provides a thread-safe dictionary for use with data binding.
    /// </summary>
    /// <typeparam name="TKey">Specifies the type of the keys in this collection.</typeparam>
    /// <typeparam name="TValue">Specifies the type of the values in this collection.</typeparam>
    [DebuggerDisplay("Count={Count}")]
    public class ObservableConcurrentDictionary<TKey, TValue> :
        ICollection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>,
        INotifyCollectionChanged, INotifyPropertyChanged
    {
        private readonly SynchronizationContext _context;
        private readonly ConcurrentDictionary<TKey, TValue> _dictionary;

        /// <summary>
        /// Initializes an instance of the ObservableConcurrentDictionary class.
        /// </summary>
        public ObservableConcurrentDictionary()
        {
            _context = AsyncOperationManager.SynchronizationContext;
            _dictionary = new ConcurrentDictionary<TKey, TValue>();
        }

        /// <summary>Event raised when the collection changes.</summary>
        public event NotifyCollectionChangedEventHandler CollectionChanged;

        /// <summary>Event raised when a property on the collection changes.</summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
        /// </summary>
        private void NotifyObserversOfChange()
        {
            var collectionHandler = CollectionChanged;
            var propertyHandler = PropertyChanged;
            if (collectionHandler != null || propertyHandler != null)
            {
                _context.Send(s =>
                {
                    collectionHandler?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Count"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Keys"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Values"));
                }, null);
            }
        }

        /// <summary>
        /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
        /// </summary>
        /// <param name="actionType">Add or Update action</param>
        /// <param name="changedItem">The item involved with the change</param>
        private void NotifyObserversOfChange(NotifyCollectionChangedAction actionType, object changedItem)
        {
            var collectionHandler = CollectionChanged;
            var propertyHandler = PropertyChanged;
            if (collectionHandler != null || propertyHandler != null)
            {
                _context.Send(s =>
                {
                    collectionHandler?.Invoke(this, new NotifyCollectionChangedEventArgs(actionType, changedItem));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Count"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Keys"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Values"));
                }, null);
            }
        }

        /// <summary>
        /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
        /// </summary>
        /// <param name="actionType">Remove action or optionally an Add action</param>
        /// <param name="item">The item in question</param>
        /// <param name="index">The position of the item in the collection</param>
        private void NotifyObserversOfChange(NotifyCollectionChangedAction actionType, object item, int index)
        {
            var collectionHandler = CollectionChanged;
            var propertyHandler = PropertyChanged;
            if (collectionHandler != null || propertyHandler != null)
            {
                _context.Send(s =>
                {
                    collectionHandler?.Invoke(this, new NotifyCollectionChangedEventArgs(actionType, item, index));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Count"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Keys"));
                    propertyHandler?.Invoke(this, new PropertyChangedEventArgs("Values"));
                }, null);
            }
        }

        /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
        /// <param name="item">The item to be added.</param>
        /// <returns>Whether the add was successful.</returns>
        private bool TryAddWithNotification(KeyValuePair<TKey, TValue> item)
            => TryAddWithNotification(item.Key, item.Value);

        /// <summary>Attempts to add an item to the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be added.</param>
        /// <param name="value">The value of the item to be added.</param>
        /// <returns>Whether the add was successful.</returns>
        private bool TryAddWithNotification(TKey key, TValue value)
        {
            bool result = _dictionary.TryAdd(key, value);
            int index = IndexOf(key);
            if (result) NotifyObserversOfChange(NotifyCollectionChangedAction.Add, value, index);
            return result;
        }

        /// <summary>Attempts to remove an item from the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be removed.</param>
        /// <param name="value">The value of the item removed.</param>
        /// <returns>Whether the removal was successful.</returns>
        private bool TryRemoveWithNotification(TKey key, out TValue value)
        {
            int index = IndexOf(key);
            bool result = _dictionary.TryRemove(key, out value);
            if (result) NotifyObserversOfChange(NotifyCollectionChangedAction.Remove, value, index);
            return result;
        }

        /// <summary>Attempts to add or update an item in the dictionary, notifying observers of any changes.</summary>
        /// <param name="key">The key of the item to be updated.</param>
        /// <param name="value">The new value to set for the item.</param>
        /// <returns>Whether the update was successful.</returns>
        private void UpdateWithNotification(TKey key, TValue value)
        {
            _dictionary[key] = value;
            NotifyObserversOfChange(NotifyCollectionChangedAction.Replace, value);
        }

        /// <summary>
        /// WPF requires that the reported index for Add/Remove events are correct/reliable. With a dictionary there
        /// is no choice but to brute-force search through the key list. Ugly.
        /// </summary>
        private int IndexOf(TKey key)
        {
            var keys = _dictionary.Keys;
            int index = -1;
            foreach(TKey k in keys)
            {
                index++;
                if (k.Equals(key)) return index;
            }
            return -1;
        }

        // ICollection<KeyValuePair<TKey,TValue>> Members


        void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
            => TryAddWithNotification(item);

        void ICollection<KeyValuePair<TKey, TValue>>.Clear()
        {
            _dictionary.Clear();
            NotifyObserversOfChange();
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
            => ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).Contains(item);

        void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
            => ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);

        int ICollection<KeyValuePair<TKey, TValue>>.Count
        {
            get => _dictionary.Count;
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
        {
            get => ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).IsReadOnly;
        }

        bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
            => TryRemoveWithNotification(item.Key, out TValue temp);


        // IEnumerable<KeyValuePair<TKey,TValue>> Members


        IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
            => _dictionary.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator()
            => _dictionary.GetEnumerator();


        // IDictionary<TKey,TValue> Members


        public void Add(TKey key, TValue value)
            => TryAddWithNotification(key, value);

        public bool ContainsKey(TKey key)
            => _dictionary.ContainsKey(key);

        public ICollection<TKey> Keys
        {
            get { return _dictionary.Keys; }
        }

        public bool Remove(TKey key)
            => TryRemoveWithNotification(key, out TValue temp);

        public bool TryGetValue(TKey key, out TValue value)
            => _dictionary.TryGetValue(key, out value);

        public ICollection<TValue> Values
        {
            get => _dictionary.Values;
        }

        public TValue this[TKey key]
        {
            get => _dictionary[key];
            set => UpdateWithNotification(key, value);
        }
    }
}