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
425 views
in Technique[技术] by (71.8m points)

c# - ObservableCollection setter isn't firing when item is added

I am working on a project in WPF using the MVVM Light framework. I have a DataGrid that is bound to an ObservableCollection<Worker>. As of now, when I add a new item, the DataGrid doesn't update and I believe it is because the setter never fires.

public ObservableCollection<Worker> MasterWorkerList
{
    get { return _masterWorkerList; }
    set 
    {
        System.Windows.MessageBox.Show("Firing");
        _masterWorkerList = value; 
        RaisePropertyChanged(() => MasterWorkerList); 
    }
}

The messagebox never displays, even when I call this:

DataManager.Data.MasterWorkerList.Add(_create.NewWorker());

How can I get RaisePropertyChanged to fire so I can update the UI?

I've tried using the solutions in this post to no avail: ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

Any advice would be appreciated. If you need more of my code, please let me know.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You shouldn't have public setters on lists for your objects. You should rather set ut up in your constructor

public MyClass(){
    _masterWorkerList = new ObservableCollection<Worker>();
    _masterWorkerList.CollectionChanged += OnCollectionChanged;
}

public ObservableCollection<Worker> MasterWorkerList
{
    get { return _masterWorkerList; }
}

private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){
    System.Windows.MessageBox.Show("Firing");
    //RaisePropertyChanged(() => MasterWorkerList); 
}

The CollectionChanged event is called when you Add something to the ObservableCollection. If you need more ingrained control you can inherit from the ObservableCollection and override the AddItem and RemoveItem methods.


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

...