ObservableCollection setter isn't firing when item is added
Asked Answered
S

2

6

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.

Souvaine answered 19/6, 2013 at 5:55 Comment(0)
H
15

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.

Helvellyn answered 19/6, 2013 at 5:59 Comment(0)
B
1

We can use CollectionChanged to notify if an Item is added or removed.

For someone who wants to bind ObservableCollection<T> myObservableCollection to some control and change UI based on item added or deleted, you can bind myObservableCollection.Count directly to XAML control. In my case I needed to check if a collection is empty in XAML and set IsVisible=False if collection is empty. Hence I did

<Button IsVisible={Binding myObservableCollection.Count, Converter={StaticResource emptyToBooleanConverter}} />

I was then passing myObservableCollection.Count to value converter and returning Boolean value false if the collection was empty. If you want the code of ValueConverter, I will provide it. BTW, I am using Xamarin.Forms (MAUI).

Broek answered 14/10, 2022 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.