Bulb Flash: Used ObservableCollection but still need INotifyPropertyChanged!!!!

Even after working on WPF/Silverlight for quite a while i always got mixed up when inspite of using an Observable Collection of items , the data binding was not automatically updated when a given item changed. Short of time as everyone else i used to end up re-setting the datacontext inspite of using the very useful ObservableCollection!!

Finally there was a “bulb flash” !!

Suppose you are binding a ListView to an  ObservableCollection<Person> called personList where Person is your custom class

  1. If you add a new Person to your ObservableCollection, the binding will get updated automatically
  2. If you change the name of the third person and expect it to show up on the screen you will be disappointed!

So, the ObservableCollection updates any increase or decrease in the “number” of elements in the collection.

If you want to dynamically update an existing element then your element will have to implement the INotifyPropertyChanged interface and manually raise the event everytime a property gets changed!.

so, what you need is

public class Person:INotifyPropertyChanged

{

private string _name;

     public string Name
     {
         get
         {
             return _name;
         }

         set
         {
             _name = value;
            RaisePropertyChanged("Name");
         }
     }

      
     protected virtual void RaisePropertyChanged(String propertName)
     {
         if ((PropertyChanged != null))
         {
             PropertyChanged(this, new PropertyChangedEventArgs     (propertyName));
         }
     }

}

Notice that if you do everything but forget to Call RaisePropertyChanged() the UI won’t get updated!!

Hope this bulb flash saves you a few hours and grey cells!!

More “Bulb Flashes” coming up!

Cennest!!