RobotDebugPageFactory.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using System.Windows;
  5. using TeamAAS.Robot.Attributes;
  6. using TeamAAS.Robot.Interfaces;
  7. namespace TeamAAS.Robot.UI
  8. {
  9. /// <summary>
  10. /// 机器人调试页工厂:按机器人类型上的 [Robot] 特性选择品牌专属调试页,
  11. /// 未指定 DebugPageType 时回退到默认调试页(DefaultRobotDebugPage,本库内)。
  12. /// 创建成功后自动把机器人实例绑定给实现了 IRobotDebugPage 的页面。永不返回 null。
  13. /// </summary>
  14. public static class RobotDebugPageFactory
  15. {
  16. public static FrameworkElement Create(IRobot robot)
  17. {
  18. Type pageType = typeof(DefaultRobotDebugPage);
  19. if (robot != null)
  20. {
  21. // [Robot] 允许多个(一个类可注册多个品牌),取第一个声明了专属页的
  22. var attr = robot.GetType().GetCustomAttributes<RobotAttribute>(inherit: false)
  23. .FirstOrDefault(a => a.DebugPageType != null && typeof(FrameworkElement).IsAssignableFrom(a.DebugPageType));
  24. if (attr != null) pageType = attr.DebugPageType;
  25. }
  26. FrameworkElement page = null;
  27. try
  28. {
  29. page = Activator.CreateInstance(pageType) as FrameworkElement;
  30. }
  31. catch (Exception ex)
  32. {
  33. System.Diagnostics.Debug.WriteLine($"创建机器人调试页 {pageType.Name} 失败: {ex.Message}");
  34. }
  35. if (page == null) page = new DefaultRobotDebugPage();
  36. if (robot != null && page is IRobotDebugPage bindable)
  37. bindable.BindRobot(robot);
  38. return page;
  39. }
  40. }
  41. }