I’ve created a handy Resharper Live Template to make creating a class that implements INotifyPropertyChanged a little easier. To implement it, do the following:
1. Create the live template
- Click Resharper->Live Templates….
- On the Template Explorer dialog Live Templates tab, click New Template.
- Enter “nprop” as the Shortcut and “INotifyPropertyChanged property” as the Description.
- Copy/paste the following into the template:
private $TYPE$ $FIELDNAME$;
public $TYPE$ $PROPERTYNAME$
{
get { return $FIELDNAME$; }
set
{
bool changed = value != $FIELDNAME$;
$FIELDNAME$ = value;
if (changed) InvokePropertyChanged(new PropertyChangedEventArgs(“$PROPERTYNAME$”));
}
} - In the macro settings, leave “TYPE” as “choose macro”, set “FIELDNAME” to “Suggest name for a variable” and “PROPERTYNAME” to “Value of FIELDNAME with the first character in uppercase” and “not editable”.
- Save settings and close Live Templates windows.
2. Using the live template
- Create a class that implements INotifyPropertyChanged:
- Put the cursor on the PropertyChanged event name, and use the Resharper Actions List (ALT+ENTER) to generate an event invocator:
- Inside the class, rather than manually typing in a property by hand, invoke the live template by typing “nprop”, then pressing TAB.
- The live template will create a property with a backing field for you, and the code necessary to invoke the event:
- Type the TypeName of the property, press TAB, then type the field name of the property.
- Press ENTER when you are done, rinse, and repeat as necessary.
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}
Hope you find it useful. Here’s a short video of it in use: INotifyPropertyChanged Resharper Live Template video.