Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify Property Changed on a Dictionary

I have a WPF / XAML form data-bound to a property in a dictionary, similar to this:

<TextBox Text="{Binding Path=Seat[2B].Name}">

Seat is exposed as a property IDictionary<String, Reservation> on the airplane object.

class airplane
{
    private IDictionary<String, Reservation> seats;
    public IDictionary<String, Reservation> Seat
    {
        get { return seats; }
        // set is not allowed
    }
}

From within the code of my Window, the value of seat 2B is sometimes changed, and after that, I want to notify the UI that the property has changed.

class MyWindow : Window
{
    private void AddReservation_Click(object sender, EventArgs e)
    {
        airplane.Seat["2B"] = new Reservation();
        // I want to override the assignment operator (=)
        // of the Seat-dictionary, so that the airplane will call OnNotifyPropertyChanged.
    }
}

I've looked to see if the Dictionary is IObservable, so that I could observe changes to it, but it doesn't seem to be.

Is there any good way to "catch" changes to the dictionary in the airplane-class so that I can NotifyPropertyChanged.

like image 208
abelenky Avatar asked Feb 11 '11 01:02

abelenky


1 Answers

Dr. WPF has created an ObservableDictionary at this link: http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/

Update: The comment made by Dr. WPF in the following link says that he has fixed this problem himself so the following change should no longer be required

Also, an addition was made at this link: http://10rem.net/blog/2010/03/08/binding-to-a-dictionary-in-wpf-and-silverlight

The small change was

// old version
public TValue this[TKey key]
{
    get { return (TValue)_keyedEntryCollection[key].Value; }
    set { DoSetEntry(key, value);}
}

// new version
public TValue this[TKey key]
{
    get { return (TValue)_keyedEntryCollection[key].Value; }
    set
    {
        DoSetEntry(key, value);
        OnPropertyChanged(Binding.IndexerName);
    }
}
like image 196
Fredrik Hedblad Avatar answered Oct 07 '22 14:10

Fredrik Hedblad