Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing Resharper's INotifyPropertyChanged

When I have a class that I declare implements then INotifyPropertyChanged interface, ReSharper will automatically generate this implementation:

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
  var handler = PropertyChanged;
  if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

which I am always editing to be this:

public event PropertyChangedEventHandler PropertyChanged = delegate { };

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
   PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Can I somehow edit the autogenerated code? Resharper's documentation is less than clear to me on this.

like image 348
Scott Baker Avatar asked Jun 29 '15 16:06

Scott Baker


People also ask

How do you use INotifyPropertyChanged?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is notify property changed?

It analyzes dependencies between fields and properties and raises a change notification for any property affected by a change in this specific field. All methods, and not just property setters, can make a change to a field and therefore cause the PropertyChanged event to be raised.

How will an object be notified if the property bound to it has been changed?

Remarks. The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .

What is PropertyChangedEventHandler C#?

When you pass the handler your object and which property changed, what does it do with them? PropertyChangedEventHandler handler = PropertyChanged; //property changed is the event if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); }


1 Answers

No, you can't edit the auto-generated code, because it needs to handle a number of possibilities when generating - e.g. C# 6 uses the ?. operator, and it also needs to handle when the event already exists and has already been initialised.

If you do want to use the shorthand version which doesn't have the local variable and the null check, then you can create the event first, and initialise it with = () => { }; before generating the OnPropertyChanged method. However, it is probably best to keep the local var + null check, for thread safety.

like image 144
citizenmatt Avatar answered Sep 19 '22 17:09

citizenmatt