Advertisement
Guest User

Untitled

a guest
Nov 1st, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. public class WpfControlFactory
  2. {
  3. public static TControl CreateWpfControl<TControl>(string name = null) where TControl : class, IWpfControl
  4. {
  5. TControl wpfControl = default(TControl);
  6.  
  7. //Avoid some bone-headed exceptions
  8. if (!typeof(TControl).IsAbstract)
  9. {
  10. wpfControl = Activator.CreateInstance<TControl>();
  11. }
  12.  
  13. if (wpfControl != null)
  14. {
  15. wpfControl.Name = name ?? Consts.DefaultEaControlName;
  16. }
  17.  
  18. return wpfControl;
  19. }
  20. }
  21.  
  22. public static IWpfControl CreateWpfControl(string controlType, string controlName)
  23. {
  24. Type type = FindType(controlType);
  25. if (type == null)
  26. {
  27. return null;
  28. }
  29.  
  30. MethodInfo method = typeof(WpfControlFactory).GetMethod("CreateInstance");
  31. MethodInfo generic = method.MakeGenericMethod(type);
  32. return (IWpfControl)generic.Invoke(null, null);
  33. }
  34.  
  35. private static Type FindType(string typeName)
  36. {
  37. Type type = null;
  38. WpfControl wpfControl;
  39. Enum.TryParse(typeName, out wpfControl);
  40. if (wpfControl != default(WpfControl))
  41. {
  42. type = Type.GetType(typeName);
  43. }
  44.  
  45. return type;
  46. }
  47.  
  48. private static TControl CreateInstance<TControl>(string name = null) where TControl : class, IWpfControl
  49. {
  50. TControl wpfControl = default(TControl);
  51.  
  52. //Avoid some bone-headed exceptions
  53. if (!typeof(TControl).IsAbstract)
  54. {
  55. wpfControl = Activator.CreateInstance<TControl>();
  56. }
  57.  
  58. if (wpfControl != null)
  59. {
  60. wpfControl.Name = name ?? Consts.DefaultEaControlName;
  61. }
  62.  
  63. return wpfControl;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement