4

I have added several elements to an ObservableCollection and now I want to modify one of them like:

_MyCollection[num].Data1 = someText;

As an example, according to code below, intention is: _MyCollection[5].Type = changedText;

_MyCollection.Add(new MyData
{
    Boundary = Text1,
    Type = Text2,
    Option = Text3
});

How can I do that?

Shibli
  • 5,879
  • 13
  • 62
  • 126
  • Similar question: http://stackoverflow.com/questions/800091/how-do-i-update-an-existing-element-of-an-observablecollection – Robar Mar 15 '12 at 10:54
  • What's the problem with `_MyCollection[5].Type = changedText;`? That should work just fine unless `MyData` is a struct. – H.B. Mar 15 '12 at 10:58

2 Answers2

6

I guess you just want to see the changes right? This has nothing to do with the ObservableCollection but with your MyData object. It has to implement INotifyPropertyChange - if you do, you will see the changes you made.

public class MyData : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string type;
    public string Type
    {
      get { return type; }
      set
      {
         if (value != type)
         {
            type = value;
            NotifyPropertyChanged("Type");
         }
      }
    }

    // ... more properties

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}
Random Dev
  • 51,810
  • 9
  • 92
  • 119
1

This will fire a CollectionChanged event:

MyData temp = _MyCollection[index];
temp.Type = changedText;
_MyCollection.SetItem(index, temp);
Mike Cowan
  • 919
  • 5
  • 11
  • true - this will work too - but if the collection is big the bound wpf-itemcontrol will have to do additional work when you only want to change the values of an item - you should not do this – Random Dev Mar 15 '12 at 11:00
  • Yes, maybe not the best solution; however, if you don't have the option of modifying the `MyData` class to implement `INotifyPropertyChanged` this will work. – Mike Cowan Mar 15 '12 at 11:09