Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c# - WPF - OnPropertyChanged for a property within a collection

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

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

    class ClassA { public bool IsEnabled { get; set; } }
}

My view has a datagrid which binds to MyCollection. Each row has a button whose "IsEnabled" attribute is bound to the IsEnabled property of ClassA.

When conditions in the view model change such that one particular item in the MyCollction list needs to bow be disabled, I set the IsEnabled property to false:

MyCollection[2].IsEnabled = false;

I now want to notify the View of this change with a OnPropertyChanged event, but I don't know how to reference a particular item in the collection.

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

both do not work.

How do I notify the View of this change? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...