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

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

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 the response, the PropertyChanged event fires as expected; but if I add a line of a line to the Response list using the Add List method, the PropertyChanged event does not fire.

I was considering adding the AddAnswer () method to my class that would handle the call of the Add Add List method and call onPropertyChanged () from there, but is this the right way to do this? Is there a more elegant way to do this?

Cheers, KT

+3
6

ObservableCollection<string>, INotifyCollectionChange, .

; .

PropertyChanged .

+14

, , , , afaikt, , ( , , , , alteast ) :

, InitializeComponent(); .

, DataContext , NotifyPropertyChanged . 2 , , MVVM userControls. , InitializeComponent(); , . , !

, , ! , Code Warrior Malo

+3

, , . Add() , , .

+1

System.Collections.ObjectModel.ObservableCollection. http://msdn.microsoft.com/en-us/library/ms668604.aspx

List, , .

+1

ObservableCollection - . , INotifyPropertyChanged , .

0

_answers. , List<T> .

As a suggestion, control _answershow ObservableCollection<string>and correctly attach / detach the event handler for the event CollectionChangedas follows:

public ObservableCollection<string> Answers
{
    get { return _answers;  }
    set
    {
      // Detach the event handler from current instance, if any:
      if (_answers != null)
      {
         _answers.CollectionChanged -= _answers_CollectionChanged;
      }

      _answers = value;

      // Attatach the event handler to the new instance, if any:
      if (_answers != null)
      {
         _answers.CollectionChanged += _answers_CollectionChanged;
      }

      // Notify that the 'Answers' property has changed:
      onPropertyChanged("Answers");
    }
}

private void _answers_CollectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
   onPropertyChanged("Answers");
}
0
source

Source: https://habr.com/ru/post/1748899/


All Articles