I'm not a fan of the INotifyPropertyChanged interface requiring that property names are passed as strings. I want a strongly-typed way to check at compile time that I'm only raising and handling property changes for properties that exist. I use this code to do that:
public static class INotifyPropertyChangedExtensions
{
public static string ToPropertyName(this Expression> @this)
{
var @return = string.Empty;
if (@this != null)
{
var memberExpression = @this.Body as MemberExpression;
if (memberExpression != null)
{
@return = memberExpression.Member.Name;
}
}
return @return;
}
}
In classes that implement INotifyPropertyChanged I include this helper method:
protected void NotifySetProperty(ref T field, T value,
Expression> propertyExpression)
{
if (field == null ? value != null : !field.Equals(value))
{
field = value;
this.NotifyPropertyChanged(propertyExpression.ToPropertyName());
}
}
So that finally I can do this kind of thing:
private string _name;
public string Name
{
get { return _name; }
set { this.NotifySetProperty(ref _name, value, () => this.Name); }
}
It's strongly-typed and I only raise events for properties that actually change their value.