views:

2385

answers:

4

Hello,

I'm trying to create a Observable Dictionary Class for WPF DataBinding in C#. I found a nice example from Andy here: http://stackoverflow.com/questions/800130/two-way-data-binding-with-a-dictionary-in-wpf/800217

According to that, I tried to change the code to following:

class ObservableDictionary : ViewModelBase
{
    public ObservableDictionary(Dictionary<TKey, TValue> dictionary)
    {
        _data = dictionary;
    }

    private Dictionary<TKey, TValue> _data;

    public Dictionary<TKey, TValue> Data
    {
        get { return this._data; }
    }

    private KeyValuePair<TKey, TValue>? _selectedKey = null;
    public KeyValuePair<TKey, TValue>? SelectedKey
    {
        get { return _selectedKey; }
        set
        {
            _selectedKey = value;
            RaisePropertyChanged("SelectedKey");
            RaisePropertyChanged("SelectedValue");
        }
    }

    public TValue SelectedValue
    {
        get
        {
            return _data[SelectedKey.Value.Key];
        }
        set
        {
            _data[SelectedKey.Value.Key] = value;
            RaisePropertyChanged("SelectedValue");
        }
    }
}

}

Unfortunately I still don't know how to pass "general" Dictionary Objects.. any ideas?

Thank you!

Cheers

+8  A: 

If you really want to make an ObservableDictionary, I'd suggest creating a class that implements both IDictionary and INotifyCollectionChanged. You can always use a Dictionary internally to implement the methods of IDictionary so that you won't have to reimplement that yourself.

Since you have full knowledge of when the internal Dictionary changes, you can use that knowledge to implement INotifyCollectionChanged.

Andy
A: 

You can't write something that will make somebody else's Dictionary, let alone IDictionary, observable without using some form of reflection. The trouble is that the Dictionary may be a subclass with additional mutators (say, Sort, or Filter, or whatever) that don't invoke Add and Remove and bypass your events as a result.

I believe code generation frameworks exist that allow you do do stuff like this but I'm not familiar with them.

reinierpost
+1  A: 

ObservableDictionary(Of TKey, TValue) - VB.NET

General feature list:

  • ObservableDictionary(Of TKey, TValue)
  • AddRange getting notified only once.
  • Generic EventArgs(Of TKey, TValue)
  • NotifyDictionaryChanging(Of TKey, TValue) - a subclass of CancelEventArgs that allows cancelling operation.
Shimmy
A: 

public class ObservableDictionary<TKey, TValue> : ObservableCollection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>>?

Observer