Maciek
Maciek

Reputation: 19893

Dictionary to ListView TwoWay binding - possible?

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?

Upvotes: 4

Views: 3063

Answers (2)

user7116
user7116

Reputation: 64098

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 and Keys collections through separate properties of the same name. These collections are of types Dictionary<TKey, TValue>.ValueCollection and Dictionary<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.

Upvotes: 2

jmayor
jmayor

Reputation: 2795

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.

Upvotes: 2

Related Questions