Automatically implementing INotifyPropertyChanged
Binding objects to the UI is a large and tedious task. You must implement
INotifyPropertyChanged on every property that needs to be bound. You need to ensure that the underlying property getter correctly raises events so that the
View knows that changes have occurred. The larger your codebase, the more work there is. You can partially elminate all of this repetitive code by pushing some of the functionality
to a base class that each Model class inherits from. It still doesn't eliminate all of the repetition though.
PostSharp can completely eliminate all of that repetition for you. All you have to do is make use of the Model Pattern Library's
INotifyPropertyChanged aspect.
- Let's add
INotifyPropertyChangedto theCustomerForEditingclass.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);} } public string Phone { get; set; } public string Mobile { get; set; } public string Email { get; set; } } - Put the caret on the class name and expand the Smart Tag. From the list select "Implement INotifyPropertyChanged".
- If you haven't previously added the Model Pattern Library to the current project, PostSharp will inform you that it will be doing this as well as adding an attribute to
the target class.
- PostSharp will download the Model Pattern Library and add the attribute.
- Once the download, installation and configuration of the Model Pattern Library and the addition of the attribute has finished you can close the wizard and look at the changes
that were made to your codebase.
- You'll notice that the code you added
INotifyPropertyChangedto has only been slightly modified. PostSharp has added aNotifyPropertyChangedattribute to the class. This class level attribute will add the implementation ofINotifyPropertyChangedto the class as well as the plumbing code in each property that makes it work.[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; } } public string Phone { get; set; } public string Mobile { get; set; } public string Email { get; set; } }Note
This example has added
INotifyPropertyChangedto one class. If you need to implementINotifyPropertyChangedto many different classes in your codebase you will want to read about using aspect multicasting
By using the Model Pattern Library to add INotifyPropertyChanged to your
Model classes you are able to eliminate all of the repetitive boilerplate coding tasks and code from the codebase.
What to read next?
Adding detailed tracing or back to Model.