views:

390

answers:

1

I have a custom class Foo with properties A and B. I want to display it in a databinding control.

I have created a class Foos : BindingList<Foo> .

In order to update some internal properties of the Foos class I need to be notified of property changes (I can handle insertions, removals etc.) on the items in the list. How would you implement that functionality ?

Should I inherit Foo from some object in the framework that supports that ? I think I could create events that notify me if changes, but is that the way it should be done ? Or is there some pattern in the framework, that would help me ?

+1  A: 

Foo should implement the INotifyPropertyChanged and INotifyPropertyChanging interfaces.

public void Foo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    private int _someValue;
    public int SomeValue
    {
        get { return _someValue; }
        set { _someValue = value; NotifyPropertyChanged("SomeValue"); }
    }
}

The BindingList should hook onto your event handler automagically, and your GUI should now update whever you set your class invokes the PropertyChanged event handler.

[Edit to add:] Additionally, the BindingList class exposted two events which notify you when the collection has been added to or modified:

public void DoSomething()
{
    BindingList<Foo> foos = getBindingList();
    foos.ListChanged += HandleFooChanged;
}

void HandleFooChanged(object sender, ListChangedEventArgs e)
{
    MessageBox.Show(e.ListChangedType.ToString());
}
Juliet
Testing ... I think it is what I am looking for.
Tomas Pajonk
What event in the Foos class will catch the fire PropertyChanged handlers ? Remember I need to some work in the Foos class (basically reworking some internal dictionaries).
Tomas Pajonk
Lets say your Foo class was implemented the same way as shown above. When any class sets the Foo.SomeValue property, the Foo instance raises the PropertyChanged event handler. You can (if you wanted to) hook onto this event handler directly on the Foo instance, or through BindingList.ListChanged.
Juliet
Thank you very much Princess. I can't give you more than upvote though :)
Tomas Pajonk