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.
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.
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.
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 .
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)); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With