views:

74

answers:

2

I have used an ObservableCollection with WPF for binding and this works well. What I really want at the moment is a Dictionary like one, that has a key that I can use, so effectively like "ObservableCollection".

Can you suggest the code that could be used to provide such an ObservableCollection? The goal is to have a Dictionary like structure that I can bind to from WPF.

Thanks

+1  A: 

Create a class that implements the IDictionary, INotifyCollectionChanged & INotifyPropertyChanged interfaces. The class would have an instance of Dictionary that it would use for the implementation of IDictionary (one of the Add methods is coded below as an example). Both INotifyCollectionChanged and INotifyProperyChanged require the presence of events, these events should be fired at appropriate points in the wrapper functions (again, consult the Add method below for an example)

class ObservableDictionary<TKey, TValue> : IDictionary, INotifyCollectionChanged, INotifyPropertyChanged
{
    private Dictionary<TKey, TValue> mDictionary;
    // Methods & Properties for IDictionary implementation would defer to mDictionary:
    public void Add(TKey key, TValue value){
        mDictionary.Add(key, value);
        OnCollectionChanged(NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value)
        return;
    }
    // Implementation of INotifyCollectionChanged:
    public event NotifyCollectionChangedEventHandler CollectionChanged;
    protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args){
        // event fire implementation
    }
    // Implementation of INotifyProperyChanged:
    public event ProperyChangedEventHandler ProperyChanged;
    protected void OnPropertyChanged(PropertyChangedEventArgs args){
        // event fire implementation
    }
}

Edit:

Note that an implementation of the IDictionary interface directly or indirectly would require that three additional interfaces be implemented:

ICollection<KeyValuePair<TKey,TValue>>
IEnumerable<KeyValuePair<TKey,TValue>>
IEnumerable.

Depending on your needs you may not have to implement the entire IDictionary interface, if you are only going to be calling a couple of the methods then just implement those methods and the IDictionary interface becomes a luxury. You must implement the INotifyCollectionChanged and INotifyPropertyChanged interfaces for binding to work however.Blockquote

Steve Ellinger
putting this into VS I note there are many more interface methods that would need implementing - is this correct?
Greg
Yes, if your requirements require you to implement the entire IDictionary interface, see my edits
Steve Ellinger
+2  A: 

Someone already made it. I haven't try it yet but nothing to lose.

ktutnik