WPF - OnPropertyChanged for a property within a collection

后端 未结 2 672
渐次进展
渐次进展 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: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

提交回复
热议问题