Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created August 13, 2018 18:51
Show Gist options
  • Save JerryNixon/f7d2a875e01e376652ba5a906690249a to your computer and use it in GitHub Desktop.
Save JerryNixon/f7d2a875e01e376652ba5a906690249a to your computer and use it in GitHub Desktop.
Generic observable dictionary.
public class ObservableDictionary<K, V> : INotifyCollectionChanged, IEnumerable<KeyValuePair<K, V>>
{
private Dictionary<K, V> _dictionary = new Dictionary<K, V>();
private void RaiseChanged(NotifyCollectionChangedAction action, params K[] keys)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(action, keys));
DictionaryChanged?.Invoke(this, new NotifyDictionaryChangedEventArgs(action, keys));
}
// INotifyCollectionChanged
public event NotifyCollectionChangedEventHandler CollectionChanged;
public event EventHandler<NotifyDictionaryChangedEventArgs> DictionaryChanged;
public class NotifyDictionaryChangedEventArgs : EventArgs
{
internal NotifyDictionaryChangedEventArgs(NotifyCollectionChangedAction action, params K[] keys)
{
Action = action;
Keys = keys;
}
public NotifyCollectionChangedAction Action { get; }
public K[] Keys { get; }
}
public void Add(K key, V value)
{
_dictionary.Add(key, value);
RaiseChanged(NotifyCollectionChangedAction.Add, key);
}
public bool Remove(K key)
{
if (_dictionary.Remove(key))
{
RaiseChanged(NotifyCollectionChangedAction.Remove, key);
return true;
}
return false;
}
public void Clear()
{
var priorKeys = _dictionary.Keys.ToArray();
_dictionary.Clear();
RaiseChanged(NotifyCollectionChangedAction.Remove, priorKeys);
RaiseChanged(NotifyCollectionChangedAction.Reset);
}
public V this[K key]
{
get => _dictionary[key];
set
{
_dictionary[key] = value;
RaiseChanged(NotifyCollectionChangedAction.Replace, key);
}
}
public int Count => _dictionary.Count;
public IEnumerable<K> Keys => _dictionary.Keys;
public IEnumerable<V> Values => _dictionary.Values;
public bool ContainsKey(K key) => _dictionary.ContainsKey(key);
public bool TryGetValue(K key, out V value)
=> _dictionary.TryGetValue(key, out value);
// IEnumerable<T>
public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
=> ((IEnumerable<KeyValuePair<K, V>>)_dictionary).GetEnumerator();
// IEnumerable
IEnumerator IEnumerable.GetEnumerator()
=> ((IEnumerable<KeyValuePair<K, V>>)_dictionary).GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment