This is the online documentation for PostSharp 5.0.
Download PDF or CHM. Go to v4.3 or v5.0

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.

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.

Example

C#
[NotifyPropertyChanged] 
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:

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

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

    C#
    ((INotifyPropertyChanged) (object) obj).PropertyChanged += obj_OnPropertyChanged;
  • You can use the Post.Cast<SourceType, TargetType>(SourceType) 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:

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