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
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.
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.
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With