.NET ObservableDictionary [英] .NET ObservableDictionary
问题描述
我已经写它实现了以下类字典通知(或试图!):
I have written the following class which implements(or tries to!) a dictionary with notifications:
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);
}
}
}
在另一个类,我有一个侦听 MyObservableDictionary.CollectionChanged
事件:
In another class, I have a listener for the MyObservableDictionary.CollectionChanged
event:
我遇到的问题是,该事件不会触发。我该如何解决这个问题?
The problem I'm having is that the event doesn't fire. How can I fix this?
推荐答案
我建议您实施的IDictionary&LT; TKEY的,TValue&GT;
,而不是继承自字典&LT; TKEY的,TValue&GT;
。因为你必须使用新
,而不是覆盖
这是可能的方法是简单地被调用基类,而不是你的类。我会忍不住使用词典&LT; TKEY的,TValue&GT;
内部做数据的实际存储
I'd suggest that you implement the IDictionary<TKey, TValue>
instead of inheriting from Dictionary<TKey, TValue>
. Since you have to use new
rather than override
it's possible that the methods are simply being called on the base class rather than your class. I'd be tempted to use a Dictionary<TKey, TValue>
internally to do the actual storing of data.
其实我发现这一点: <一href="http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx">http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx
In fact I found this: http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx
这篇关于.NET ObservableDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!