开发者

Observable dictionary not behaving as expected

I want to have Dictionary that would be 'Observable' in order to throw events when its item changing (Remove or Add).

In other class I created such dictionary and set Binding to ListBox.ItemsSourseProperty.

The Binding work well. I can see the items.

But something is wrong: the event PropertyChanged always null.

Can anyone开发者_如何学C help?

Thanks in advance!

class ObservableDictionary<TKey, TValue> : 
    Dictionary<TKey, TValue>, 
    INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public new void Remove(TKey obj)
    {
        base.Remove(obj);

        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Remove"));
        }
    }
}


You should not call PropertyChanged for a collection change event. You need to implement INotifyCollectionChanged.


Did you subscribe the PropertyChanged event?

var dictionary = new ObservableDictionary<int, int>();
dictionary.PropertyChanged += 
    ( sender, args ) => MessageBox.Show( args.PropertyName );
dictionary.Add( 1, 2 );
dictionary.Remove( 1 );

This works for me.

But it would be cleaner to implement the interface IDictionary instead of using the new keyword. Then you can use a private Dictionary instance within your class to safe you the work of implementing everything on your own.


Is anyone subscribing to Propertychanged?

For an observable collection, you are going to also want INotifyCollectionChanged


It sounds like you may be looking for a dictionary version of ObservableCollection (see: MSDN), which implements both INotifyCollectionChanged and INotifyPropertyChanged out of the box. Perhaps looking over its implementation in reflector may be helpful? It can be found in the System.Collections.ObjectModel namespace in the System.dll assembly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜