Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...