System.ComponentModel.INotifyPropertyChanged

This interface has a single event called PropertyChanged.
Classes that implement this interface can raise the PropertyChanged event when one of the properties are changed.
The most common use of this is in a Model-View-Presenter design pattern when you need a property of the model to update something in the view (via the presenter).
The model will implement the INotifyPropertyChanged interface.

public class MyClass : System.ComponentModel.INotifyPropertyChanged 
{
   public event PropertyChangedEventHandler PropertyChanged;

   private void Method_OnPropertyChanged(string name)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(name);
      }
   }

   private string _name;

   public string Property_Name
   {
      get { return value; }
      set
      {
         if (_name != value)
         {
            _name = value;
            this.Method_OnPropertyChanged("name");
         }
      }
   }
}

This approach has a few disadvantages:
The property names are hard-coded as strings. It is very easy to mistype the name or use the wrong name.
If the properties change frequently and performance is essential it is not very efficient to create a new EventArgs object every time a property changes.


C# 5.0 / .NET 4.5

This has become easier thanks to the introduction of new Caller Information Attributes
The presence of the [CallerMemberName] attribute means that you do not need to specify the property name when the method is called from inside a property setter.

private void Method_PropertyChanged([CallerMemberName] string caller = null) 
{
   if (PropertyChanged != null)
   {
         PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(caller);
   }
}

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext