using System;
using System.Reflection;
using System.Windows;
using TeamAAS.Communication.Attributes;
using TeamAAS.Communication.Interfaces;
namespace TeamAAS.Communication.UI
{
///
/// 通讯设备调试页工厂:按设备类型上的 [Communication] 特性选择品牌专属调试页,
/// 未指定 DebugPageType 时回退到默认调试页(DefaultCommunicationDebugPage,本库内)。
/// 创建成功后自动把设备实例绑定给实现了 ICommunicationDebugPage 的页面。永不返回 null。
///
public static class CommunicationDebugPageFactory
{
public static FrameworkElement Create(ICommunication communication)
{
Type pageType = typeof(DefaultCommunicationDebugPage);
if (communication != null)
{
var attr = communication.GetType().GetCustomAttribute(inherit: true);
if (attr != null && attr.DebugPageType != null && typeof(FrameworkElement).IsAssignableFrom(attr.DebugPageType))
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 DefaultCommunicationDebugPage();
if (communication != null && page is ICommunicationDebugPage)
((ICommunicationDebugPage)page).BindCommunication(communication);
return page;
}
}
}