I'm attempting to bind a Dictionary to a ListView who's item template constist of a grid with 2 textboxes. Ideally I'd like to be able to modify both the key and the value of the KeyValuePair displayed in the ListView . Is that possible?
If you look at the KeyValuePair implementation it is a struct with both Key and Value as readonly Properties so my guess is that it's not possible to make a TwoWay binding in this case.
If you make a class that inherits INotifyPropertyChange that handles dictionary add and remove items when you change the key or that only change the value when you are changing the value perhaps it works.
What you're looking for is something akin to an ObservableCollection<T>
but for a dictionary. A bit of Googling found the following from Dr. WPF on building an ObservableDictionary
:
Pros and Cons
The benefit to using an observable dictionary, of course, is that the dictionary can serve as the ItemsSource for a databound control and you can still access the dictionary in code the same way you access any other dictionary. It is truly an indexed dictionary of objects. There are certainly some limitations inherent in the very idea of making a dictionary observable. Dictionaries are built for speed. When you impose the behaviors of an observable collection on a dictionary so that the framework can bind to it, you add overhead.
Also, a dictionary exposes its
Values
andKeys
collections through separate properties of the same name. These collections are of typesDictionary<TKey, TValue>.ValueCollection
andDictionary<TKey, TValue>.KeyCollection
, respectively. These CLR-defined collections are not observable. As such, you cannot bind to the Values collection or to the Keys collection directly and expect to receive dynamic collection change notifications. You must instead bind directly to the observable dictionary.
Now, you may run into a problem with updating the Key, as you would then need to somehow convince the dictionary to Move your item. I would suggest taking Dr. WPF's ObservableDictionary
and instead using a KeyedCollection
as the backing store. That way the Key is derived from the Item itself, and updates move the object in the ObservableDictionary
automatically.