0

I've defined an Observable collection as shown below,

public class PropertyFieldsInExcel
{
    public string LongNames { get; set; }
    public string ShortNames { get; set; }
    public string CNames { get; set; }                              
}

static ObservableCollection<PropertyFieldsInExcel> Properties = 
    new ObservableCollection<PropertyFieldsInExcel>();

I have a method which changes the the value of some of the elements in that class like so,

public static void AutofillCell()
{            
    ((INotifyPropertyChanged)Properties).PropertyChanged += 
        new PropertyChangedEventHandler(PropertyChangedEvent);            

    Properties[i].CNames = "It works";
    Properties[i].CNames = "Ha ha ha";            

    ((INotifyPropertyChanged)Properties).PropertyChanged -= 
        new PropertyChangedEventHandler(PropertyChangedEvent);
}

When I assign a value to a particular element as shown above, the event does not fire. Why? What is the mistake I've committed?

The code of the event handler is like so,

private static void PropertyChangedEvent(object sender, PropertyChangedEventArgs e)
{
    //Some code to be executed
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Rama
  • 1,019
  • 1
  • 15
  • 34
  • 1
    Possible duplicate of [ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)](http://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyprop) – Uwe Keim Jun 03 '16 at 10:19
  • Are you not looking for the CollectionChanged event? – momar Jun 03 '16 at 10:21
  • No, the collectionChanged event will not fire for sure. According to MSDN it fires only when we add, remove, replace or change the whole object. Here I'm changing a property inside the object – Rama Jun 03 '16 at 10:23

1 Answers1

1

Two problems:

1) PropertyFieldsInExcel does not implement INotifyPropertyChanged

2) ObservableCollection can inform you when items are changing, but only after you manually subcribe to the changed event of all items.

The link in the comment from Uwe Keim gives an exellent explanation with examples...

Community
  • 1
  • 1
Dieter Meemken
  • 1,937
  • 2
  • 17
  • 22