Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChange ~ PropertyChanged not firing when property is a collection and a new item is added to the collection

I have a class that implements the INotifyPropertyChanged interface. Some of the properties of the class are of type List. For example:

public List<string> Answers
{
    get { return _answers;  }
    set
    {
      _answers = value;
      onPropertyChanged("Answers")
    }
}

...

private void onPropertyChanged(string propertyName)
{
    if(this.PropertyChanged != null)
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

If I assign a new List<string> to Answer, then the PropertyChanged event fires as expected; but if I add a string string to the Answer list using the List Add method, then PropertyChanged event doesn't fire.

I was considering adding an AddAnswer() method to my class, which would handle calling the lists's Add method and would call onPropertyChanged() from there, but is that the right way to do it? Is there a more elegant way of doing it?

Cheers, KT

like image 653
eponymous23 Avatar asked Jun 07 '10 17:06

eponymous23


People also ask

When should I use the propertychanged event?

When you bind to a property (even if that property is an ObservableCollection), any changes to the PROPERTY (not the contents of the property) should raise the PropertyChanged event.

What is the use of INotifyPropertyChanged class?

So the usage of this class is just like ObservableCollection, however, it only allows classes that implement the INotifyPropertyChanged interface. This class is simple but powerful. It simply registers to the PropertyChanged event of the item and calls OnCollectionChanged of the ObservableCollection when the item raises the PropertyChanged event.

How does the observablecollection register for a propertychanged event?

It simply registers to the PropertyChanged event of the item and calls OnCollectionChanged of the ObservableCollection when the item raises the PropertyChanged event. As usual, one should be very careful about the memory leaks when there are event subscriptions involved. So, make sure to call the Clear...

What is the difference between selecteditem and propertychanged events?

This means if the SelectedItem was changed the event fires inside the class the property contains ( MainWindowViewModel in your case). The PositionViewModel is not recognizing if it is selected or not. The PropertyChanged event of it is only called if a property inside itself was changed.


1 Answers

You should expose an ObservableCollection<string>, which implements the INotifyCollectionChange interface to raise its own change events.

You should also remove the property setter; Collection properties should be read only.

You should not raise the PropertyChanged event when the contents of the collection change.

like image 80
SLaks Avatar answered Sep 27 '22 02:09

SLaks