WPF - OnPropertyChanged for a property within a collection

后端 未结 2 670
渐次进展
渐次进展 2020-12-06 19:46

In a view model, I have a collection of items of type \"ClassA\" called \"MyCollection\". ClassA has a property named \"IsEnabled\".

class MyViewModel 
{
           


        
相关标签:
2条回答
  • 2020-12-06 20:06

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

    0 讨论(0)
  • 2020-12-06 20:22

    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 like Scott said

    EDIT2: made invoking PropertyChanged event shorter

    0 讨论(0)
提交回复
热议问题