What is the best way to specify a property name when using INotifyPropertyChanged?
Most examples hardcode the property name as an argument on the PropertyChanged E
Yet another approach: http://www.codeproject.com/Articles/450688/Enhanced-MVVM-Design-w-Type-Safe-View-Models-TVM
Additionally, we found an issue where getting a method name worked differently in Debug vs. Release builds:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/244d3f24-4cc4-4925-aebe-85f55b39ec92
(The code we were using wasn't exactly reflection in the way you suggested, but it convinced us that hardcoding the property name was the fastest and most reliable solution.)
Roman:
I'd say you wouldn't even need the "Person" parameter - accordingly, a completely generic snippet like the one below should do:
private int age;
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChanged(() => Age);
}
}
private void OnPropertyChanged<T>(Expression<Func<T>> exp)
{
//the cast will always succeed
MemberExpression memberExpression = (MemberExpression) exp.Body;
string propertyName = memberExpression.Member.Name;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
...however, I prefer sticking to string parameters with conditional validation in Debug builds. Josh Smith posted a nice sample on this:
A base class which implements INotifyPropertyChanged
Cheers :) Philipp
You might be interessted in this discussion about
"Best Practices: How to implement INotifyPropertyChanged right?"
too.