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

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

关于c# - .NET ObservableDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5663395/

10-12 12:54