Reputation: 66320
I have a Helper method like this to get me the PropertyName (trying to avoid magic strings)
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
var body = (MemberExpression) expression.Body;
return body.Member.Name;
}
However sometimes my PropertyNames aren't named well either. So I would like to rather use the DisplayAttribute.
[Display(Name = "Last Name")]
public string Lastname {get; set;}
Please be aware I am using Silverlight 4.0. I couldnt find the usual namespace DisplayAttributeName attribute for this.
How can I change my method to read the attribute (if available) of th eproperty instead?
Many Thanks,
Upvotes: 14
Views: 9885
Reputation: 14784
This should work:
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression propertyExpression = (MemberExpression)expression.Body;
MemberInfo propertyMember = propertyExpression.Member;
Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
if(displayAttributes != null && displayAttributes.Length == 1)
return ((DisplayAttribute)displayAttributes[0]).Name;
return propertyMember.Name;
}
Upvotes: 26