Software & Finance





WPF ListBox Binding – Overriding Interface INotifyPropertyChanged and using PropertyChangedEventHandler





If you have data binding and if you are changing the properties at run time, it needs to be notified to the corresponding GUI item such as ListBox, TextBox, ComboBox, etc. Consider ListBox is our GUI Item in this example. If we add a new datacontext to the listbox, the listbox can update its view. But if you modify one property (City) one existing item in the data context (Instance of StudentInformation), then listbox has no way of knowing that the property has been modified.

To notify the GUI item, we need to override the interface INotifyPropertyChanged interface for the class which we use it in datacontext property.

If we do not override INotifyPropertyChanged and do not make the call to PropertyChangedEventHandler, WPF ListBox would work fine when you initialize the data context and would not update if you modify the data context at run time.

 

public class StudentInformation : INotifyPropertyChanged

   {

      public string name;

      public string city;

 

      public event PropertyChangedEventHandler PropertyChanged;

 

      protected void NotifyPropertyChanged(string property)

      {

         if (PropertyChanged != null)

         {

            PropertyChanged(this, new PropertyChangedEventArgs(property));

         }

      }

 

      public string Name

      {

         get

         {

            return name;

         }

         set

         {

            name = value; NotifyPropertyChanged("Name");

         }

      }

 

      public string City

      {

         get

         {

            return city;

         }

         set

         {

            city = value; NotifyPropertyChanged("City");

         }

      }

 

      public override string  ToString()

      {

            return Name + " " + City;

      }

 

   }