.NET ObservableDictionary
我编写了以下类,该类实现(或尝试!)带有通知的字典:
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
事件监听器:
我遇到的问题是该事件不会触发。我怎样才能解决这个问题?
回答:
我建议您实现IDictionary<TKey, TValue>
而不是从继承Dictionary<TKey,
TValue>。由于您必须使用new
而不是使用override
方法,因此有可能只是在基类而不是您的类上调用了这些方法。我很想在Dictionary<TKey,
TValue>内部使用内部存储数据。
实际上,我发现了这一点:http :
//blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-
lt-tkey-tvalue-
gt-c.aspx
以上是 .NET ObservableDictionary 的全部内容, 来源链接: utcz.com/qa/403570.html