Bigeyes
Bigeyes

Reputation: 1666

Update ObservableCollection element not working

I have one ObservableCollection in my ViewModel with INotifyPropertyChanged, say A. Now I am going to loop through A to get some elements updated.

public ObservableCollection<ClassA> A
{
    get
    {
        if (this.a== null)
        {
            this.a= new ObservableCollection<ClassA>();
        }
        return this.a;
    }
    set
    {
        this.a= value;
        this.OnPropertyChanged("A");// implement PropertyChangedEvent
    }
}

In the loop I update the values.

foreach (var item in MyViewModel.A)
{
    if(condition)
       MyViewModel.A.Type= "CASH";
    else
       MyViewModel.A.Type= "CHECK";
}

But I see the setter part is not reached. so the collection is not updated.

Upvotes: 0

Views: 175

Answers (2)

Bigeyes
Bigeyes

Reputation: 1666

I use my own method. By using generic list to retrieve the all items from Observable Collection. Then convert the generic list to the Observable Collection.

It is not the best way but so far it works out.

Upvotes: 1

Ewen Cochran
Ewen Cochran

Reputation: 86

It looks like you're trying to update the elements in the ObservableCollection<ClassA> and not setting the collection to a new value. If you want a property change to occur when calling MyViewModel.A.Type = "CASH" then ClassA will need to implement INotifyPropertyChanged.

(EDIT: For others seeing this, check this question/answer - I'm not able to mark this as a possible duplicate. You need to monitor for property changes of elements in the collection and then trigger the property change on your ObservableCollection manually. The container does not do this for you.)

Upvotes: 4

Related Questions