System.ComponentModel.INotifyPropertyChanged

This interface has a single event called PropertyChanged.
You can use this property changed event to notify you when an object property changes.
Classes that implement this interface can raise the PropertyChanged event when one of their properties changes
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.
The model will implement the INotifyPropertyChanged interface.


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

   private void Method_PropertyChanged(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_PropertyChanged("name");
      }
   }
}

This approach has a few disadvantages:

1) The property names are hard-coded as strings. It is very easy to mistype the name or use the wrong name.

2) 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(name);
   }
}




© 2017 Better Solutions Limited. All Rights Reserved. © 2017 Better Solutions Limited

Top

PrevNext