Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect changes to item properties in the BindingList<T>?

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 ?

like image 232
Tomas Pajonk Avatar asked Mar 17 '09 17:03

Tomas Pajonk


People also ask

How do I sort BindingList?

A quick way to implement a Sort on a BindingList is to use the constructor that takes a backing IList< T > as its argument. You can use a List<T> as the backing and gain its Sort capabilities.

How to bind object in c#?

The Binding class is used to bind a property of a control with the property of an object. For creating a Binding object, the developer must specify the property of the control, the data source, and the table field to which the given property will be bound.

What is BindingList in C#?

BindingList is a generic list type that has additional binding support. While you can bind to a generic list, BindingList provides additional control over list items, i.e. if they can be edited, removed or added. BindingList also surfaces events that notify when the list has been changed.


Video Answer


1 Answers

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 automatically, and your GUI should now update whenever you set your class invokes the PropertyChanged event handler.

[Edit to add:] Additionally, the BindingList class expose 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());
}
like image 132
Juliet Avatar answered Sep 19 '22 15:09

Juliet