PostSharp 6.5 / / Post­Sharp Documentation / INotify­Property­Changed / Implementing INotify­Property­Changed

Implementing INotifyPropertyChanged

This section shows how to make your class automatically implements the INotifyPropertyChanged interface NotifyPropertyChangedAttribute aspect.

This topic contains the following sections:

Adding the NotifyPropertyChanged aspect

To add INotifyPropertyChanged aspect:

  1. Use NuGet Package Manager to add the PostSharp.Patterns.Model package to your project.

  2. Import the PostSharp.Patterns.Model namespace into your file.

  3. Add the [NotifyPropertyChanged] custom attribute to the class.

All properties of the class now fire the PropertyChanged event whenever they are changed. You can prevent a property from automatically firing the PropertyChanged event with IgnoreAutoChangeNotificationAttribute.

By using the Model Pattern Library to add NotifyPropertyChangedAttribute to your model classes you are able to eliminate all of the repetitive boilerplate coding tasks and code from the codebase.

Note Note

This procedure has added NotifyPropertyChangedAttribute to one class. If you need to implement NotifyPropertyChangedAttribute to many different classes in your codebase you will want to read about using aspect multicasting. See the section Adding Aspects to Multiple Declarations.


public class CustomerForEditing 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public string FullName  
        get { return string.Format("{0} {1}", this.FirstName, this.LastName); }  

Consuming the INotifyPropertyChanged interface

Since the INotifyPropertyChanged interface is implemented by PostSharp at build time after the compiler has completed, the interface will neither be visible to Intellisense or other tools like Resharper, neither to the compiler. The same is true for the PropertyChanged event.

In many cases, this limitation does not matter because the interface is consumed from a framework (like WPF) that is not coupled with your project. However, in some situations, you may need to access the INotifyPropertyChanged interface.

There are two ways to access the INotifyPropertyChanged interface from your code:

  • You can cast your object to INotifyPropertyChanged, for instance:

    ((INotifyPropertyChanged) obj).PropertyChanged += obj_OnPropertyChanged;

    If your tooling complains that the object does not implement the interface, you can first cast to object:

    ((INotifyPropertyChanged) (object) obj).PropertyChanged += obj_OnPropertyChanged;
  • You can use the Post.Cast<TSource, TTarget>(TSource) method. The benefit of using this method is that the cast operation is validated by PostSharp, to the build will fail if you try to cast an object that does not implement the INotifyPropertyChanged interface. For instance:

    Post.Cast<Foo,INotifyPropertyChanged>(obj).PropertyChanged += obj_OnPropertyChanged;
See Also