0

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.

lorond
  • 3,856
  • 2
  • 37
  • 52
Bigeyes
  • 1,508
  • 2
  • 23
  • 42

2 Answers2

4

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.)

Community
  • 1
  • 1
  • No, I did it. ClassA implements INotifyPropertyChanged already. – Bigeyes Aug 23 '16 at 12:58
  • Ok. Suggest looking at this [question](http://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyprop). They seem to be doing something similar to you. – Ewen Cochran Aug 23 '16 at 13:02
  • I tried it. It is not working well as it includes ADD/REMOVE. I want replace part code. – Bigeyes Aug 23 '16 at 13:04
  • @Bigeyes, are you sure the set method is firing and the property changed event executed when ClassA is being modified? – dev1998 Aug 23 '16 at 13:10
  • @dev1998. Yes. I am sure. I am thinking that can I use a list first. Update the list then convert the list to ObservableCollection. Not sure if it is okay. – Bigeyes Aug 23 '16 at 13:13
  • One of the answers in the link from @Ewen Cochran is using a temporary list. Look at the answer by thinksomid. – dev1998 Aug 23 '16 at 13:42
0

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.

Bigeyes
  • 1,508
  • 2
  • 23
  • 42