CommunicationDebugPageFactory.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Reflection;
  3. using System.Windows;
  4. using TeamAAS.Communication.Attributes;
  5. using TeamAAS.Communication.Interfaces;
  6. namespace TeamAAS.Communication.UI
  7. {
  8. /// <summary>
  9. /// 通讯设备调试页工厂:按设备类型上的 [Communication] 特性选择品牌专属调试页,
  10. /// 未指定 DebugPageType 时回退到默认调试页(DefaultCommunicationDebugPage,本库内)。
  11. /// 创建成功后自动把设备实例绑定给实现了 ICommunicationDebugPage 的页面。永不返回 null。
  12. /// </summary>
  13. public static class CommunicationDebugPageFactory
  14. {
  15. public static FrameworkElement Create(ICommunication communication)
  16. {
  17. Type pageType = typeof(DefaultCommunicationDebugPage);
  18. if (communication != null)
  19. {
  20. var attr = communication.GetType().GetCustomAttribute<CommunicationAttribute>(inherit: true);
  21. if (attr != null && attr.DebugPageType != null && typeof(FrameworkElement).IsAssignableFrom(attr.DebugPageType))
  22. pageType = attr.DebugPageType;
  23. }
  24. FrameworkElement page = null;
  25. try
  26. {
  27. page = Activator.CreateInstance(pageType) as FrameworkElement;
  28. }
  29. catch (Exception ex)
  30. {
  31. System.Diagnostics.Debug.WriteLine($"创建通讯调试页 {pageType.Name} 失败: {ex.Message}");
  32. }
  33. if (page == null) page = new DefaultCommunicationDebugPage();
  34. if (communication != null && page is ICommunicationDebugPage)
  35. ((ICommunicationDebugPage)page).BindCommunication(communication);
  36. return page;
  37. }
  38. }
  39. }