Implementing INotifyPropertyChanging

By convention, the PropertyChanged event must be raised after the property value has changed. However, some components need to be signalled before the property value will be changed. This is the role of the INotifyPropertyChanging interface.

Because the INotifyPropertyChanging interface is not portable (in Xamarin, it is even a part of a different namespace), PostSharp cannot introduce it. However, if you implement the INotifyPropertyChanging interface yourself in your code, PostSharp will signal the PropertyChanging event. To make that work, you need to create a OnPropertyChanging method with the right signature.

To add the INotifyPropertyChanging interface to a class:

  1. Make your class implement INotifyPropertyChanging and add the PropertyChanging event:

    C#
    public class Foo : INotityPropertyChanging
    {
        public event PropertyChangingEventHandler PropertyChanging;
    }
  2. Add the OnPropertyChanging method:

    C#
    public class Foo : INotityPropertyChanging
    {
        public event PropertyChangingEventHandler PropertyChanging;
    
        protected void OnPropertyChanging( string propertyName )
        {
           if ( this.PropertyChanging != null )
           {
              this.PropertyChanging( this, new PropertyChangingEventArgs ( propertyName ) );
           }
        }
    }
  3. Add the NotifyPropertyChangedAttribute aspect to your class as described in INotifyPropertyChanged.

    C#
    [NotifyPropertyChanged]                
    public class Foo : INotityPropertyChanging
    {
        public event PropertyChangingEventHandler PropertyChanging;
    
        protected void OnPropertyChanging( string propertyName )
        {
           if ( this.PropertyChanging != null )
           {
              this.PropertyChanging( this, new PropertyChangingEventArgs ( propertyName ) );
           }
        }
    }
Note Note

The contract between your class and the NotifyPropertyChangedAttribute is only the OnPropertyChanging method. As long as this method exists in the class, it will be invoked by the aspect before the value of a property changes.