Is it possible to rewrite this extension method without the parameter?
public static string PropertyName<T>(this T obj, Expression<Func<T>> property)
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Expression must be a MemberExpression.", "property");
return memberExpression.Member.Name;
}
This is the test code for the function.
string TEST = Guid.NewGuid().ToString();
string propertyName = TEST.PropertyName(() => TEST);
This is the result:
propertyName = "TEST"
I would like to rewrite the code to this:
string propertyName = TEST.PropertyName();
Ps. I'm not interested in a static version of this method!
For those how doesn’t see the point of this function. In MVVM pattern you have notify changed for a property. Like this.
this.RaisePropertyChanged("TEST");
This is a bad approach since the property name is hardcoded. With help of the extension method you will have this:
this.RaisePropertyChanged(()=>Test);
I would like to rewrite the extension method to this:
this.RaisePropertyChanged(Test.PropertyName());
Below is a code sample from my MVVM project. (this is a Model property)
public DateTime Start
{
get { return WorkModel.Start; }
set
{
if (WorkModel.Start != value)
{
WorkModel.Start = new DateTime(SelectedDate.Year, SelectedDate.Month, SelectedDate.Day, value.Hour, value.Minute, value.Second);
this.RaisePropertyChanged("Start");
this.RaisePropertyChanged("TotalWork");
}
}
}