This answer is very similar to Joe White's answer above, but the code is a bit more concise and perhaps a little more understandable, as property names should not be sent as a string in quotation marks.
Using the CallerMemberName functionality, there are two ways to do this. One is to create an abstract class that contains IPropertyNotifyChanged code, and another approach is to include the IPropertyNotifyChanged support code in a real class. I usually use both depending on the context.
Here's what the results look like when using an abstract class:
public abstract class PropertyNotifier: INotifyPropertyChanged { #region INotifyPropertyChanged support code public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null) { bool result = false; if (!Object.Equals(storage, value)) { storage = value; OnPropertyChanged(propertyName); result = true; } return result; } #endregion INotifyPropertyChanged support code }
And in use:
public interface IPerson { String FirstName { get; set } String LastName { get; set } } public class Person : PropertyNotifier, IPerson { private string _FirstName; private string _LastName; public String FirstName { get { return _FirstName; } set { SetProperty(ref _FirstName, value); } } public String LastName { get { return _LastName; } set { SetProperty(ref _LastName, value); } } }
Hope this helps!
source share