It must be a somewhat common event to change the name of a property and expect the Rename functionality in Visual Studio to take care of all the necessary renaming, except f
The simplest solution is to look at the stack trace and completly remove every explicit reference to the property.
public String Name
{
get { return this.name; }
set
{
if (value != this.name)
{
this.RaisePropertyChanging();
this.name = value;
this.RaisePropertyChanged();
}
}
}
private String name = null;
private void RaisePropertyChanged()
{
String propertyName =
new StackTrace().GetFrame(1).GetMethod().Name.SubString(4);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(new PropertyChangedEventArgs(propertyName));
}
}
The code derives the property name through the stack trace from the caling method - that is the property setter method named set_<PropertyName>
. If the compiler no longer follows this naming convention, the code breaks.
The other solution is to derive the property name from a lambda expression.
public static String GetPropertyNameFromLambdaExpression<TObject, TProperty>(
Expression<Func<TObject, TProperty>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
For example
GetPropertyNameFromLambdaExpression<String, Int32>(s => s.Length)
will return "Length
" as exspected. A production version of the code really demands additional checks and better integration into the rest of the code. For example it is possible to use type inference for the generic arguments.
UPDATE
And there is a third solution - you can use MethodBase.GetCurrentMethod()
inside a property getter or setter to obtain the name of the setter or getter method.
public String Name
{
get { return this.name; }
set
{
if (value != this.name)
{
String propertyName = MethodBase.GetCurentMethod().Name.SubString(4);
this.RaisePropertyChanging(propertyName);
this.name = value;
this.RaisePropertyChanged(propertyName);
}
}
}
private String name = null;