WinForms 适配器
把通道事件和点表变化切到 UI 线程,并提供控件绑定,避免每个窗体手写 InvokeRequired。
var attachment = this.AttachZeus(builder => builder.AddVirtualChannel("meter"));
var meter = attachment.Host.Channels.Get("meter");
meter.BindState(stateLabel);
meter.BindText(echoLabel);
meter.BindText(hexLabel, ChannelTextFormatter.Hex);
meter.BindEnabled(sendButton);
程序集:Zeus.Presentation.WinForms(目标框架 net8.0-windows)。
API
| API | 作用 |
|---|---|
Form.AttachZeus(...) | Load 时启动,FormClosed 时释放 |
host.AttachManually() | 只创建挂接,不绑窗口;适合登录后进入主界面或托盘常驻 |
BindText | 把数据写到 Control.Text |
BindState | 显示通道状态 |
BindEnabled | 按通道状态设置 Control.Enabled,默认仅 Open 时启用 |
AsBindingSource(control) | INotifyPropertyChanged 投影 |
points.BindText("temperature", label) | 把点表值写到控件 |
points.BindSnapshot("temperature", control, action) | 把完整点快照推到 UI 线程 |
points.BindGauge("temperature", progressBar) | 按报警限把当前值映射到进度条 |
points.AsBindingSource("temperature", control) | 单点 INotifyPropertyChanged 投影 |
alarms.BindAlarms(control, action) | 把活动报警列表推到 UI 线程 |
alarms.AsAlarmBindingSource(control) | 报警队列 INotifyPropertyChanged 投影 |
points.BindEnabled("setpoint", button) | 按点可写状态和错误状态控制按钮 |
points.BindAlarmBackColor / BindAlarmForeColor | 按报警和错误状态切换颜色 |
points.BindWriteBack | 把按钮点击绑定为 Points.WriteAsync |
ChannelTextFormatter.Default / Hex | ASCII 或十六进制 |
控件已销毁或尚未创建句柄时,更新会被丢弃。
BindEnabled 常用于发送按钮,避免通道还没打开时点击发送:
meter.BindEnabled(sendButton);
// 如果希望 Opening 时也允许操作,可以传入自定义规则。
meter.BindEnabled(sendButton, state => state is ChannelState.Opening or ChannelState.Open);
点表绑定
点表绑定适合直接显示采集值、报警状态和写回按钮状态:
points.BindText("temperature", temperatureLabel, value => $"{value:0.0} C");
points.BindAlarmBackColor("temperature", temperatureLabel);
points.BindSnapshot("temperature", alarmLabel, snapshot =>
{
alarmLabel.Text = snapshot.AlarmState.ToString();
});
points.BindEnabled("setpoint", writeButton);
points.BindWriteBack(
"setpoint",
setpointTextBox,
writeButton,
text => double.Parse(text, CultureInfo.InvariantCulture),
ex => MessageBox.Show(this, ex.Message, "写回失败", MessageBoxButtons.OK, MessageBoxIcon.Warning));
如果已经使用 WinForms 数据绑定,可以直接绑定单点投影:
var source = points.AsBindingSource("temperature", this);
temperatureLabel.DataBindings.Add("Text", source, nameof(PointBindingSource.Text));
alarmLabel.DataBindings.Add("Text", source, nameof(PointBindingSource.AlarmState));
几个 Label、报警色和写回按钮用上面的逐点绑定即可。DataGrid、总貌或一屏几十个点,请改用 points.AsTableBindingSource(this):它只是把内核的 BatchChanged 投影成可绑定列表,一轮刷新一次。不要给每个点各绑一次再在 Changed 里 Clear/Add。写回输入框继续逐点绑定,避免整表刷新盖掉正在编辑的值。点表事件本身与界面无关,对照见 点表与采集。
趋势图或历史报表由业务层订阅 points.Changed / points.BatchChanged 后自行存储和刷新,Zeus 不内置点历史缓存或图表适配。多点趋势优先订 BatchChanged。
常见问题
- 出现跨线程异常:请使用本程序集的
BindText、BindState或点表绑定扩展,不要直接在DataReceived里改控件。 - 关闭窗口后串口仍被占用:使用
AttachZeus,不要自己Start却忘记释放。 - 要绑定
Text以外的属性:优先看是否已有专用绑定,例如通道按钮启用状态用meter.BindEnabled,点表报警颜色用points.BindAlarmBackColor;其它属性可用BindSnapshot自己映射。