.NET ObservableDictionary

前端 未结 6 1265
感情败类
感情败类 2020-11-27 03:07

I have written the following class which implements(or tries to!) a dictionary with notifications:

public partial class ObservableDictionary

        
6条回答
  •  旧巷少年郎
    2020-11-27 03:24

    I have managed to find a solution - workaround

    public delegate void CollectionAlteredEventHander( object sender , EventArgs e);
    
    public partial class ObservableDictionary : Dictionary
    {
    
        /*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 observableDictionary, TKey key , ref int idx)
        {
            foreach (KeyValuePair 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);
            }
        }
    
    }
    

    I've no longer implement the INotifyCollectionChanged interface though.

提交回复
热议问题