Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 311
Jason D Avatar asked Jun 19 '13 05:06

Jason D


1 Answers

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.

like image 75
default Avatar answered Nov 15 '22 08:11

default