| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System;
- using System.Linq;
- using System.Reflection;
- using System.Windows;
- using TeamAAS.Robot.Attributes;
- using TeamAAS.Robot.Interfaces;
- namespace TeamAAS.Robot.UI
- {
- /// <summary>
- /// 机器人调试页工厂:按机器人类型上的 [Robot] 特性选择品牌专属调试页,
- /// 未指定 DebugPageType 时回退到默认调试页(DefaultRobotDebugPage,本库内)。
- /// 创建成功后自动把机器人实例绑定给实现了 IRobotDebugPage 的页面。永不返回 null。
- /// </summary>
- public static class RobotDebugPageFactory
- {
- public static FrameworkElement Create(IRobot robot)
- {
- Type pageType = typeof(DefaultRobotDebugPage);
- if (robot != null)
- {
- // [Robot] 允许多个(一个类可注册多个品牌),取第一个声明了专属页的
- var attr = robot.GetType().GetCustomAttributes<RobotAttribute>(inherit: false)
- .FirstOrDefault(a => a.DebugPageType != null && typeof(FrameworkElement).IsAssignableFrom(a.DebugPageType));
- if (attr != null) pageType = attr.DebugPageType;
- }
- FrameworkElement page = null;
- try
- {
- page = Activator.CreateInstance(pageType) as FrameworkElement;
- }
- catch (Exception ex)
- {
- System.Diagnostics.Debug.WriteLine($"创建机器人调试页 {pageType.Name} 失败: {ex.Message}");
- }
- if (page == null) page = new DefaultRobotDebugPage();
- if (robot != null && page is IRobotDebugPage bindable)
- bindable.BindRobot(robot);
- return page;
- }
- }
- }
|