WPF - OnPropertyChanged for a property within a collection

In the view model, I have a set of elements of type "ClassA" called "MyCollection". ClassA has the property "IsEnabled".

class MyViewModel { List<ClassA> MyCollection { get; set; } class ClassA { public bool IsEnabled { get; set; } } } 

My view has a datagrid that binds to MyCollection. Each line has a button, the attribute "IsEnabled" is attached to the IsEnabled property of class A.

When the conditions in the view model change so that one specific item in the MyCollction list should be disabled, I set the IsEnabled property to false:

 MyCollection[2].IsEnabled = false; 

Now I want to notify the view of this change with the OnPropertyChanged event, but I do not know how to refer to a specific element in the collection.

 OnPropertyChanged("MyCollection"); OnPropertyChanged("MyCollection[2].IsEnabled"); 

both do not work.

How do I notify a view of this change? Thanks!

+4
source share
2 answers

ClassA needs to implement INotifyPropertyChanged:

 class ClassA : INotifyPropertyChanged { private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { if (value != _isEnabled) { _isEnabled = value; OnPropertyChanged("IsEnabled"); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } 

EDIT: and use an ObservableCollection as Scott said.

EDIT2: PropertyChanged event call shorter

+12
source

Instead of using a list, try using an ObservableCollection. Also, modify your ClassA so that it implements INotifyPropertyChanged, especially for the IsEnabled property. Finally, modify your MyViewModel class so that it also implements INotifyPropertyChanged, especially for the MyCollection property.

+6
source

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


All Articles