Created
July 22, 2011 07:56
-
-
Save dalager/1099049 to your computer and use it in GitHub Desktop.
GetDisplayNameFor<MyType>(x=>x.MyProperty);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Get the DataAnnotation attributed DisplayName attribute value. | |
/// </summary> | |
/// <example> | |
/// GetDisplayNameFor<VagtTyper>(x => x.Doegnvagt) ==> "Døgnvagt" | |
/// </example> | |
/// <typeparam name="TSource"></typeparam> | |
/// <param name="propLambda"></param> | |
/// <returns></returns> | |
public string GetDisplayNameFor<TSource>(Expression<Func<TSource,object>> propLambda) | |
{ | |
var expression = propLambda.Body; | |
var unaryExp = expression as UnaryExpression; | |
if (unaryExp != null) | |
{ | |
var memberExp = (MemberExpression)unaryExp.Operand; | |
var dna = memberExp.Member | |
.GetCustomAttributes(typeof(DisplayNameAttribute), true) | |
.Cast<DisplayNameAttribute>() | |
.FirstOrDefault(); | |
return dna == null ? memberExp.Member.Name : dna.DisplayName; | |
} | |
throw new ArgumentException("Only properties can be used in this method"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A quick take on using the System.ComponentModel.DataAnnotations.DisplayNameAttribute like this:
var displayName = GetDisplayNameFor(x=>x.MyProperty);
Where
class MyType{
[DisplayName("Something Foo")]
public bool MyProperty{get;set;}
}