code_junkie

Get class property name

Nov 11th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. [AttributeUsage(AttributeTargets.Property)]
  2. class TextProperyAttribute: Attribute
  3. {}
  4.  
  5. class MyTextBox
  6. {
  7. [TextPropery]
  8. public string Text { get; set;}
  9. public int Foo { get; set;}
  10. public double Bar { get; set;}
  11. }
  12.  
  13.  
  14. static string GetTextProperty(Type type)
  15. {
  16. foreach (PropertyInfo info in type.GetProperties())
  17. {
  18. if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0)
  19. {
  20. return info.Name;
  21. }
  22. }
  23.  
  24. return null;
  25. }
  26.  
  27. ...
  28.  
  29. Type type = typeof (MyTextBox);
  30.  
  31. string name = GetTextProperty(type);
  32.  
  33. Console.WriteLine(name); // Prints "Text"
  34.  
  35. private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector)
  36. {
  37. var memberExpression = propertySelector.Body as MemberExpression;
  38. return memberExpression != null
  39. ? memberExpression.Member.Name
  40. : string.empty;
  41. }
  42.  
  43. this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty),
  44. this.myDataSourceObject,
  45. "Text");
Add Comment
Please, Sign In to add comment