Thursday, September 11, 2014

Property changed event handler

If you want the implementation of the INotifyPropertyChanged interface..
public event PropertyChangedEventHandler PropertyChanged;

void OnPropertyChanged(string property)
{
 PropertyChangedEventHandler handler = this.PropertyChanged;
 if (handler != null)
  handler(this, new PropertyChangedEventArgs(property));
}



..more explicit, you can't just change the PropertyChanged implementation to this:
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;

void OnPropertyChanged(string property)
{
 PropertyChangedEventHandler handler = this.PropertyChanged;
 if (handler != null)
  handler(this, new PropertyChangedEventArgs(property));
}


It will have this error:
An explicit interface implementation of an event must use event accessor syntax


Must do this:
PropertyChangedEventHandler _propertyChanged;
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
 add { _propertyChanged += value; }
 remove { _propertyChanged -= value; }
}

void OnPropertyChanged(string property)
{
 PropertyChangedEventHandler handler = this._propertyChanged;
 if (handler != null)
  handler(this, new PropertyChangedEventArgs(property));
}  


Happy Coding!

No comments:

Post a Comment