using System.Collections.ObjectModel;
using System.Windows.Input;
using UIShare.PubEvent;
using UIShare.UIViewModel;
using UIShare.ViewModelBase;
namespace SettingModule.ViewModels.Dialogs
{
///
/// VISA 连接配置对话框 VM。
/// 通过 DialogParameters 接收宿主 DeviceInfoVM;保存时把副本写回宿主。
///
public class VisaConfigViewModel : DialogViewModelBase
{
#region 属性
private string _title = "VISA 连接配置";
public string Title
{
get => _title;
set => SetProperty(ref _title, value);
}
/// 编辑用的副本,取消时不会污染宿主对象。
private VisaConfigVM _config = new();
public VisaConfigVM Config
{
get => _config;
set => SetProperty(ref _config, value);
}
/// 常用超时(毫秒)。
public ObservableCollection CommonTimeouts { get; } = new()
{
500, 1000, 2000, 3000, 5000, 10000
};
/// 常见 VISA 资源字符串模板,便于快速填写(可直接编辑)。
public ObservableCollection ResourceTemplates { get; } = new()
{
"TCPIP0::192.168.20.125::inst0::INSTR",
"TCPIP0::192.168.20.125::5025::SOCKET",
"USB0::0x0699::0x0408::C012345::INSTR",
"GPIB0::7::INSTR",
"ASRL1::INSTR"
};
private string _errorMessage = string.Empty;
public string ErrorMessage
{
get => _errorMessage;
set => SetProperty(ref _errorMessage, value);
}
#endregion
#region 命令
public ICommand SaveCommand { get; }
public ICommand CancelCommand { get; }
#endregion
// 用于保存时把副本回写到原对象
private DeviceInfoVM? _hostDevice;
public VisaConfigViewModel(IContainerProvider containerProvider) : base(containerProvider)
{
SaveCommand = new DelegateCommand(OnSave);
CancelCommand = new DelegateCommand(OnCancel);
}
private bool Validate(out string error)
{
error = string.Empty;
if (string.IsNullOrWhiteSpace(Config.ResourceName))
{
error = "VISA 资源字符串不能为空";
return false;
}
if (!Config.ResourceName.Contains("::"))
{
error = "资源字符串格式不正确,应形如 TCPIP0::192.168.0.10::inst0::INSTR";
return false;
}
if (Config.OpenTimeout < 0 || Config.IOTimeout < 0)
{
error = "超时时间不能为负数";
return false;
}
return true;
}
private void OnSave()
{
if (!Validate(out var error))
{
ErrorMessage = error;
return;
}
ErrorMessage = string.Empty;
// 把副本写回宿主
if (_hostDevice != null)
{
_hostDevice.VisaConfig ??= new VisaConfigVM();
Config.CopyTo(_hostDevice.VisaConfig);
_hostDevice.ConnectionType = "Visa";
}
RequestClose.Invoke(ButtonResult.OK);
}
private void OnCancel() => RequestClose.Invoke(ButtonResult.Cancel);
#region Prism Dialog 规范
public override void OnDialogOpened(IDialogParameters parameters)
{
_eventAggregator.GetEvent().Publish(true);
if (parameters.ContainsKey("Device"))
{
_hostDevice = parameters.GetValue("Device");
Title = $"VISA 连接配置 - {_hostDevice?.DeviceName}";
Config = new VisaConfigVM(_hostDevice?.VisaConfig);
}
else if (parameters.ContainsKey("Config"))
{
Config = new VisaConfigVM(parameters.GetValue("Config"));
}
}
public override void OnDialogClosed()
{
_eventAggregator.GetEvent().Publish(false);
}
#endregion
}
}