Strongly-typed Names for INotifyPropertyChanged
A number of people have asked whether it is possible to implement INotifyPropertyChanged without hard-coding property names as strings inside code.
For example, you would normally write:
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
Unfortunately the default refactoring tools won't search in string literals, so if LastName
was renamed to Surname
, you'd need to change the string manually.
One option to enforce compile-time detection would be the following:
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged(Property.GetFor( () => this.Name ));
}
}
It could be implemented quite simply with the following static method:
public class Property
{
public static PropertyChangedEventArgs GetFor(Expression<Func<object>> propertyNameLambda)
{
MemberExpression member = propertyNameLambda.Body as MemberExpression;
if (member != null)
{
return new PropertyChangedEventArgs(member.Member.Name);
}
return new PropertyChangedEventArgs("");
}
}
Personally, I don't mind hard-coding property names too much, but it's hardly a best practices, so you may find the above useful. Just beware that it does come with some overhead at runtime.