Shibli
Shibli

Reputation: 6149

Modify an item of ObservableCollection

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?

Upvotes: 4

Views: 7684

Answers (2)

Mike Cowan
Mike Cowan

Reputation: 919

This will fire a CollectionChanged event:

MyData temp = _MyCollection[index];
temp.Type = changedText;
_MyCollection.SetItem(index, temp);

Upvotes: 1

Random Dev
Random Dev

Reputation: 52300

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));
        }
    }
}

Upvotes: 6

Related Questions