Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable dictionary not behaving as expected

Tags:

c#

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 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"));
        }
    }
}
like image 995
yossharel Avatar asked May 18 '10 14:05

yossharel


4 Answers

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

like image 166
Stephen Cleary Avatar answered Nov 19 '22 02:11

Stephen Cleary


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.

like image 26
tanascius Avatar answered Nov 19 '22 02:11

tanascius


Is anyone subscribing to Propertychanged?

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

like image 2
JMarsch Avatar answered Nov 19 '22 03:11

JMarsch


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.

like image 2
Jesse Squire Avatar answered Nov 19 '22 02:11

Jesse Squire