🖥️ WpfUI-Skill — WPF 现代化界面开发
一句话: 用户描述界面需求 → AI 自动生成完整可运行的 WPF 应用程序
🎯 用途
帮助用户基于 Snet WPF 框架快速构建现代化桌面应用,涵盖窗口管理、MVVM 绑定、主题切换、多语言、内置控件、拖拽等完整能力。
控件选择规则(使用本技能时必须遵守)
- 先在
Snet.Windows.Controls查找满足当前交互能力的内置控件;内置不存在该能力时,使用Wpf.Ui.Controls。禁止为了方便、沿用旧示例或补样式而回退到System.Windows.Controls原生交互控件。Snet/Wpf.Ui 控件内部继承或使用原生控件是库的实现细节,不改变调用方的优先级。 - 布局与文档基础元素可以保留:
Grid、RowDefinition、ColumnDefinition、StackPanel、DockPanel、WrapPanel、Canvas、Border、Viewbox、Application、ResourceDictionary、Style、ControlTemplate、DataTemplate、Binding、Run,以及自定义视图的UserControl/Page根元素。这些不作为按钮、输入、选择、导航、数据显示等交互控件的回退。受限子项布局使用内置snet:StackPanelEx,分隔调整使用snet:DockPanelSplitter。 - 先核对属性再替换类型。
ButtonControl是包装UserControl,Content为string,只有Command,不能假设有按钮的Click/CommandParameter;复合内容或需要CommandParameter的按钮能力内置未提供时使用wpfui:Button。TextBoxControl提供Text/Hint/ClearButtonEnabled,没有多行、只读和TextChanged公开事件;需要这些能力时优先用内置snet:TextBoxEx,代码编辑/高亮用snet:TextEditorControl。 - 不知道如何实现时,先检查开源 Debug 和 Daq 的 WPF 端。本轮核对本地
F:/Snet/Debug@429cb40be03e0fa5c69121ea0469b29a5a7fb066、F:/Snet/Daq@0a7d5c9a8117cb91c3d5940507103edf6e1d43a6的 XAML、ViewModel、主题与绑定,再按本规则改写。参考项目仍有原生控件,参考其行为与结构不表示可以直接复制违反规则的标签。 - 两层库均无对应能力时,先用已有 Snet/Wpf.Ui 组件组合实现;确实需要新增控件或改变交互时说明缺口。不得虚构
wpfui:GroupBox、wpfui:ContextMenu、wpfui:CheckBox等不存在的类型,也不得偷偷回退原生控件。
完整根元素按需声明以下命名空间;片段沿用所在根元素的声明:
xmlxmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" xmlns:h="clr-namespace:Snet.Windows.Controls.handler;assembly=Snet.Windows.Controls"
| 需求 | 必须优先选用 | 真实属性 / 边界 |
|---|---|---|
| 文本/图标按钮 | snet:ButtonControl | Content、Icon、Command、CornerRadius;复杂内容能力缺失时才用 wpfui:Button |
| 单行输入 | snet:TextBoxControl | Text、Hint、ClearButtonEnabled |
| 多行/只读文本、文本事件 | snet:TextBoxEx | 继承 TextBox,支持 Text、AcceptsReturn、IsReadOnly、TextChanged、ScrollToEnd() |
| 代码/日志编辑与高亮 | snet:TextEditorControl | h:EditBindingHandler.EditText 绑定,ShowLineNumbers、IsReadOnly、WordWrap |
| 普通文本 | snet:TextBlockEx | Text、TextWrapping;独立使用合并 TextBlockEx/Generic.xaml |
| 下拉选择 | snet:ComboBoxControl | ItemsSource、SelectedItem、DisplayMemberPath、Hint |
| 枚举单选 / 布尔状态标记 | snet:RadioButtonList / snet:CheckMark | EnumType/Value / IsChecked;CheckMark 是标记,开关交互用 wpfui:ToggleSwitch.IsChecked |
| 数值 / 滑块 | snet:SpinControl / snet:HeaderedEntrySlider / snet:SliderEx | Value、Minimum、Maximum、SmallChange、LargeChange |
| 表格 | snet:DataGrid | ItemsSource 为 IList;手动列为 ColumnDefinitions + snet:ColumnDefinition(PropertyName, Header),不能套用原生 .Columns 或 DataGridTextColumn |
| 树形 / 属性编辑 | snet:TreeListBox / snet:PropertyControl / snet:PropertyGrid | HierarchySource、ChildrenPath / BasicsData / SelectedObject |
| 颜色 / 文件 / 目录 | snet:ColorPicker / snet:FilePicker / snet:DirectoryPicker | SelectedColor / FilePath / Directory |
| 弹层 / 链接 | snet:PopupBox / snet:LinkBlock | PopupTemplate / Text、NavigateUri |
| LED / 分页 / 托盘 | snet:LedGaugeControl / snet:PageBarControl / snet:NotifyIcon | 按本技能对应章节的真实属性 |
| 导航 / 搜索建议 | wpfui:NavigationView / wpfui:AutoSuggestBox | MenuItemsSource、FooterMenuItemsSource / PlaceholderText;Snet 没有同类顶层控件 |
| 分组卡片 | wpfui:Card / wpfui:CardExpander | 使用卡片中的 StackPanel + snet:TextBlockEx 标题;不生成原生 GroupBox |
| 密码 / 进度 | wpfui:PasswordBox / wpfui:ProgressRing | Snet 没有同类独立交互控件 |
| 通知 / 页签 | wpfui:InfoBar / wpfui:TabView | 不以原生同类控件回退 |
| 消息 / 自定义对话框 | Snet MessageBox.Show / DialogHandler.ShowAsync | 使用 WindowBase 现有宿主及队列,不能任意新建同名 DialogHost |
snet:DataGrid、snet:PropertyGrid、ColorPicker 等独立使用的样式合并见 §6.2。wpfui: 控件资源已由 Snet 深浅主题合并。NotifyIcon.Menu 的真实类型仍是原生 ContextMenu,不是 Wpf.Ui 控件;本技能生成的新界面不创建它,使用托盘左键恢复主窗口,再用主窗口中的 Snet 按钮提供操作。
✨ 能力
- 🪟 现代化窗口基类 —
WindowBase自定义窗口,含标题栏按钮、DPI 感知、加载动画 - 🎨 深色/浅色主题 — Material Design + Wpf.Ui 双主题引擎,一键切换
- 🌍 中英文多语言 —
LocExtension/BLoc标记扩展,运行时热切换 - 🧩 MVVM 架构 —
BindNotify基类 +InjectionWpfDI 容器 +EventCommand行为 - 🎛️ 内置控件库(全) — ButtonControl / ComboBoxControl / TextBoxControl / LedGaugeControl / PageBarControl / TextEditorControl / PropertyControl / NotifyIcon / 消息对话框
- 🧰 property/wpf 子控件(20+) — ColorPicker / FilePicker / DirectoryPicker / RadioButtonList / SpinControl / FormattingTextBox / HeaderedEntrySlider / TextBoxEx / EditableTextBlock / CheckMark / EnumMenuItem / DockPanelSplitter / StackPanelEx / PopupBox / LinkBlock / PropertyGrid / DataGrid(内置版)/ TreeListBox / ItemsBag / PropertyDialog / WizardDialog(见 §6.2 全览)
- 🔧 PropertyGrid — 属性编辑器,含 ColorPicker、FilePicker、DataGrid、TreeListBox
- 🖱️ 拖拽控件 — 8 向缩放手柄 + 拖拽移动 + 动画拖拽创建
- 💬 消息对话框 — OK / OKCancel / Yes / YesNo 四种模式,Material Design 风格
- 🔔 系统托盘 —
NotifyIcon最小化到托盘,右键菜单 - 📐 Win32 集成 — 窗口消息处理、DWM 背景色同步、最大化补偿、窗口抖动
🗣️ 交互流程
AI 先用大白话问用户:
- 🏷️ 窗口需求 — 窗口标题、是否需要皮肤/语言切换、有无图标
- 🎨 主题偏好 — 默认深色还是浅色
- 🌍 语言需求 — 中文 / 英文 / 中英切换
- 🎛️ 需要哪些控件 — 按钮、下拉框、输入框、属性编辑、LED、分页
- 📊 数据绑定 — ViewModel 结构、命令、数据源
确认后生成完整代码。
⚡ 快速开始
NuGet 安装
安装基线 26.316.1 已于 2026-11-13 核对 NuGet;源码项目版本 1.0.0.0 与内部 ProjectReference 是构建配置,不用于安装命令。当前源码行为可能晚于发布包,生成代码时按实际安装包核验,不能把源码更新自动归入该包。
bash# 核心库(必装) dotnet add package Snet.Windows.Core -v 26.316.1 # 控件库(按需) dotnet add package Snet.Windows.Controls -v 26.316.1
当前工作树目标框架为 net10.0-windows;net11.0-windows,示例程序及测试为 net11;这是未提交源码配置,不用于断言旧安装基线包支持 net11。
当前源码依赖关系(Snet 内部使用 ProjectReference,不是发布包依赖证明)
Snet.Windows.Controls ├── Snet.Windows.Core (ProjectReference) │ ├── MaterialDesignThemes (>= 5.4.0) │ ├── WPF-UI (>= 4.3.0) │ ├── CommunityToolkit.Mvvm (>= 8.4.2) │ ├── Microsoft.Xaml.Behaviors.Wpf(EventCommand/Interaction.Triggers 依赖) │ ├── System.Management (11.0.0) │ ├── System.Drawing.Common (11.0.0) │ └── Snet.Core (ProjectReference) └── (v26.222.1 起 AvalonEdit 依赖已移除——代码编辑器源码已内嵌,见"编辑控件"章节)
🪟 第一章:WindowBase 窗口基类
概述
WindowBase 继承 System.Windows.Window,提供以下能力:
| 功能 | 属性 | 默认值 | 说明 |
|---|---|---|---|
| 皮肤切换 | SkinEnabled | true | 标题栏显示皮肤切换按钮 |
| 语言切换 | LanguageEnabled | true | 标题栏显示语言切换按钮 |
| 标题靠左 | TitleLeft | true | false 时标题居中 |
| 版本显示 | VerEnabled | true | 底部状态栏显示版本号 |
| 加载动画 | LoadAnimationEnabled | false | 淡入淡出过渡效果 |
| 动画时长 | AnimationTime | 2000 | 毫秒 |
| 最大化补偿 | MaximizeBorderThickness | 0,0,0,0 | 最大化时的内边距补偿(⚠️ 由 WindowBase 按系统边框+DPI 自动计算并覆盖,勿手动设置) |
最小示例
App.xaml:
xml<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- 深色主题 --> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Core;component/themes/DarkTheme.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/TextBlockEx/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/DataGrid/Generic.xaml" /> <!-- 或浅色主题 --> <!-- <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Core;component/themes/LightTheme.xaml" /> --> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
MainWindow.xaml:
xml<snet:WindowBase x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" Title="我的应用" Icon="/Icon.ico" LanguageEnabled="True" SkinEnabled="True" WindowStartupLocation="CenterScreen" Height="600" Width="900"> <Grid> <snet:TextBlockEx Text="Hello, Snet WPF!" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </snet:WindowBase>
⚠️
Icon="/Icon.ico"要求项目根目录存在该文件且 Build Action 为 Resource——文件缺失时应用启动即抛 IOException(无法定位资源)。无图标时可直接删除该属性。同理适用于 §10/§14 示例中的Icon="/icon.ico"。
MainWindow.xaml.cs:
csharpnamespace MyApp; public partial class MainWindow : Snet.Windows.Core.WindowBase { public MainWindow() { InitializeComponent(); } }
当前源码的窗口、属性编辑与输入行为
WindowBase在 DPI 变化时更新 X/Y 比例及最大化补偿;可选模板按钮缺失不会导致加载失败。纯代码创建的窗口可以 Show(样式不再重复设置 AllowsTransparency)。关闭窗口即使 Closed 订阅者抛异常仍释放对话框队列和原生背景画刷。注册表标记写入失败仅记录日志,同进程不反复尝试。InjectionWpf缓存的 Window 在真正 Closed 后自动移除;再次cache: true得到新实例,UserControl/Page 缓存不受影响。三个异步解析入口继续传播OperationCanceledException。SkinHandler.SetSkin应在 UI 线程调用;先替换主题、更新 MaterialDesign/Wpf.Ui,再尝试持久化,最后通知。成功保存时回调读取到新皮肤;保存失败记录日志但仍通知。ReplaceResources保持旧合并字典位置,保留宿主之后的覆盖优先级。EventSkinResult复制构造保留 Time;无参构造的 Time 为当前时间。- Windows
LanguageHandler自己负责语言配置、缓存和 WPF Culture,不是单纯薄转发;事件仍在Snet.Core.handler.LanguageHandler.OnLanguageEventAsync。同步 SetLanguage 与异步 SetLanguageAsync 分别实现;异步先检查取消并尝试写文件,再更新缓存/Culture并通知。可恢复写入失败只记一次日志,新语言仍在进程内生效;取消不被吞掉。直接使用 Core 语言处理器不会更新 Windows language.json。 IconsHandler.GetIcon的含 DynamicResource 的 DrawingImage 不能冻结并属于创建线程。UI 线程共享缓存;后台线程每次创建独立实例,不污染 UI 缓存。缺 key 抛 KeyNotFoundException。外部字典失败时保留内置图标,移除坏缓存并传播原异常;后台同步 Loading 不等待 UI 工作,失败记录日志;需要等待完成时用 LoadingAsync。PropertyGrid重套模板会强制重建并恢复选中页。可选/单选标签与描述提示随语言更新;普通标签保留被编辑对象的 DataContext;两种描述布局遵循 ToolTipTemplate,空描述无提示。英文描述走 GetLocalizedDescription;仅重写 GetLocalizedString 的本地化器仍有兼容回退。描述符缓存逐个比较实例,DataRowView/实例级 TypeDescriptionProvider 不串用属性。- INotifyDataErrorInfo 逐属性展示错误、逐 Tab 汇总,第二个属性错误或部分错误修复会刷新已有行。ErrorsChanged 可来自后台线程,同一模型显示在多个 UI Dispatcher 时分别调度,失效弱登记会清理。内置 DataGrid 在尚未连接 PresentationSource 的合成鼠标事件中不再调用 PointToScreen。
内置DataGrid的Generic.xaml仍含固定浅色:HeaderBackgroundBrush为#dfe3e8,当前单元格背景为White。仅合并DarkTheme不能保证表格全部内部状态适配深色;完整深色需求应显式提供适配的样式/模板,仍使用内置DataGrid,不回退原生控件。默认编辑菜单也是库内模板的一部分,中文只读展示可按真实RowsContextMenu/ColumnsContextMenu/SheetContextMenu属性关闭它们。
FormattedTimeSpanParser.TryParse(string value, out TimeSpan result)对空白、整串不匹配、数字/TimeSpan 溢出返回 false(result 为默认值);Parse 失败抛 FormatException,不再静默返回零。匹配允许首尾空白,仍采用 TimeSpan 构造的分量归一化语义。PasswordHelper附加到非 PasswordBox 时忽略;写回异常仍复位内部状态。其绑定值是明文 string。DirectoryPicker的默认浏览对话框传入所属窗口;BrowseForFolderDialog 使用 Unicode 路径,任何结果都释放 PIDL,复用实例无 owner 时只清除由该实例设置的旧句柄。EditBindingHandler.EditTextProperty元数据默认 null,GetEditText 返回空串;空字符串初始源也会订阅文本变化并回写。字面量搜索的 ReplaceWith 保留$&/$$等替换语义和忽略大小写时实际匹配文字;FoldingMargin 删除过期行标记前不访问已删除行 Offset。TextBoxControl.Height/ComboBoxControl.Height是有意隐藏 FrameworkElement.Height 的独立依赖属性(默认 30);它控制内部控件,真正布局高度需 SetValue(FrameworkElement.HeightProperty, value)。ButtonControl.Content 同样有意隐藏为 string。NotifyIcon的 FocusOnLeftClick、MenuOnRightClick、MenuFontSize(默认 14)运行时变更立即同步;Menu=null 清除旧菜单。NotifyIconService.Icon 更新即刷新;SetParentWindow 仅在真正 Closed 时释放,取消 Closing 后隐藏到托盘仍保留图标。- LED 的
Range<T>/Range<T,U>本轮主要补充契约注释,Empty 显式初始化为 default,没有新增 LED 依赖属性。端点构造排序;零宽区间视为空,区间包含/交集按实现处理;标量 Contains 仍检查闭区间;Range<T,U>(start,width)不排序负宽度结果。请勿把注释补全当作全新的算法。
窗口抖动效果
csharp// 调用静态方法产生抖动(如输入验证失败时) WindowBase.WindowShake(this); // 或对指定窗口抖动 WindowBase.WindowShake(someWindow);
🧩 第二章:MVVM 架构
BindNotify 基类
BindNotify 继承 ObservableObject,提供基于表达式的类型安全属性系统,无需手动声明后备字段:
csharpusing Snet.Windows.Core.mvvm; public class MainViewModel : BindNotify { // 获取属性 public string UserName => GetProperty(() => UserName); // 设置属性(仅通知) public void SetUserName(string value) => SetProperty(() => UserName, value); // 设置属性(带回调 — 接收旧值;⚠️ 同名同参重载无法共存,以下两个带回调 // 示例为不同重载示意,实际使用时仅保留一个方法) public void SetUserNameWithOldValue(string value) => SetProperty(() => UserName, value, oldValue => { Console.WriteLine($"用户名从 {oldValue} 变更为 {value}"); }); // 设置属性(带回调 — 无参) public void SetUserNameNoArg(string value) => SetProperty(() => UserName, value, () => { Console.WriteLine("用户名已更新"); }); }
优势: 无需手动声明 private string _userName 后备字段,属性值存储在内部线程安全的 Dictionary<string, object> 中,SetProperty 自动触发 OnPropertyChanged。
EventCommand 行为
将任意 WPF 事件绑定到 ViewModel 中的 ICommand(EventCommand : TriggerAction<DependencyObject>,来自 Microsoft.Xaml.Behaviors.Wpf 包——Snet.Windows.Core 已传递依赖,使用前需在 XAML 声明 xmlns:b="http://schemas.microsoft.com/xaml/behaviors"):
xml<!-- 窗口根元素需声明 xmlns:b="http://schemas.microsoft.com/xaml/behaviors" --> <snet:TextBoxEx Text="{Binding SearchText}"> <b:Interaction.Triggers> <b:EventTrigger EventName="TextChanged"> <snet:EventCommand Command="{Binding TextChangedCommand}" /> </b:EventTrigger> </b:Interaction.Triggers> </snet:TextBoxEx>
InjectionWpf 依赖注入
自动创建 View 并注入 ViewModel 作为 DataContext:
csharpusing Snet.Windows.Core.handler; // 创建 Window 并注入 ViewModel(Transient 默认不缓存) var window = InjectionWpf.Window<MainWindow, MainViewModel>(); // 创建 UserControl 并注入 ViewModel var control = InjectionWpf.UserControl<MyControl, MyViewModel>(); // 缓存模式(Singleton) var cachedWindow = InjectionWpf.Window<MainWindow, MainViewModel>(cache: true);
同步的 Window / UserControl / Page 解析路径保持真正同步,不再通过异步方法阻塞等待。当前控件可靠性约束还包括:HeaderedEntrySlider.EntryContentAlignment 正确写入对应属性;DataGrid 保留行并约束列索引;WrapItemsOperator 对空输入返回 0、部分行向上取整;FoldingManager 忽略空/反向区间;BitmapSourceTypeConverter 对 null 或不支持类型抛 NotSupportedException;IconsHandler 通过 UI Dispatcher 更新。
窗口注入示例
csharp// 在 App.xaml.cs 中重写 OnStartup protected override void OnStartup(StartupEventArgs e) { var mainWindow = InjectionWpf.Window<MainWindow, MainViewModel>(); mainWindow.Show(); }
🎨 第三章:主题系统
SkinHandler 皮肤管理
csharpusing Snet.Windows.Core.handler; using Snet.Windows.Core.@enum; // 获取当前皮肤(仅同步;SkinHandler 不支持异步操作) SkinType current = SkinHandler.GetSkin(); // 设置皮肤 SkinHandler.SetSkin(SkinType.Dark); // 深色 SkinHandler.SetSkin(SkinType.Light); // 浅色
持久化: 皮肤设置自动保存到 {AppContext.BaseDirectory}/config/skin.json。
事件通知:
csharp// 同步事件 SkinHandler.OnSkinEvent += (sender, e) => { Console.WriteLine($"皮肤切换到: {e.Skin}"); // 事件参数属性为 Skin(非 SkinType) }; // 异步事件(自动顺序执行多个异步处理器) SkinHandler.OnSkinEventAsync += async (sender, e) => { await Task.Delay(100); Console.WriteLine($"主题已切换: {e.Skin}"); };
主题资源
| 资源 Key | 用途 |
|---|---|
WindowBackgroundBrush | 窗口背景色 |
CaptionActiveBackgroundBrush | 标题栏背景渐变 |
TitleForeground | 标题字体颜色 |
VerBackgroundBrush | 底部版本栏背景 |
ImageColor | 图标颜色 |
ButtonMouseOverBackground | 按钮悬停背景 |
CloseButtonMouseOverBackground | 关闭按钮悬停背景(粉红色) |
自定义皮肤颜色
在 App.xaml 的 WindowBaseStyle 应用前覆盖资源:
xml<SolidColorBrush x:Key="WindowBackgroundBrush" Color="#1E1E2E" /> <SolidColorBrush x:Key="TitleForeground" Color="#CDD6F4" />
🌍 第四章:多语言系统
LanguageHandler 语言管理
csharpusing Snet.Windows.Core.handler; using Snet.Model.@enum; // 获取当前语言 LanguageType current = LanguageHandler.GetLanguage(); // 设置语言(Windows 层负责配置持久化、缓存和 WPF Culture;新代码可使用异步版) await LanguageHandler.SetLanguageAsync(LanguageType.zh); // 中文 await LanguageHandler.SetLanguageAsync(LanguageType.en); // 英文 // 获取翻译文本 string? text = LanguageHandler.GetLanguageValue("Hello"); string? text = await LanguageHandler.GetLanguageValueAsync("Hello"); // 使用指定程序集的资源 var model = new LanguageModel("MyApp", "Language", "MyApp.dll"); string? text = LanguageHandler.GetLanguageValue("Hello", model);
双命名空间: Windows
LanguageHandler提供配置文件、缓存、WPF Culture 和翻译转发;语言事件OnLanguageEventAsync仍在Snet.Core.handler.LanguageHandler。两个命名空间同时引入时使用全限定名或别名。
LocExtension XAML 标记扩展
xml<!-- 基础用法:通过 Key 查找翻译 --> <snet:TextBlockEx Text="{snet:Loc Hello}" /> <!-- 带类型转换(如 SolidColorBrush) --> <snet:TextBlockEx Foreground="{snet:Loc Accent, Converter={StaticResource ColorBrushConverter}}" /> <!-- 强制指定语言 --> <snet:TextBlockEx Text="{snet:Loc Hello, ForceCulture=zh}" />
BLoc 绑定扩展
xml<!-- BLoc 继承自 Binding,可作为绑定源使用 --> <snet:TextBlockEx Text="{snet:BLoc Hello}" /> <!-- 强制指定语言 --> <snet:TextBlockEx Text="{snet:BLoc Hello, ForceCulture=zh}" />
资源文件配置
在 XAML 根元素上声明默认程序集和字典:
xml<snet:WindowBase xmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" snet:ResxLocalizationProvider.DefaultAssembly="MyApp" snet:ResxLocalizationProvider.DefaultDictionary="Language" ...>
对应的 .resx 资源文件:
Language.resx (默认 — 中文) Language.en.resx (英文翻译)
🎛️ 第五章:内置控件
本章覆盖可直接使用的顶层内置控件(ButtonControl / ComboBoxControl / TextBoxControl / LedGaugeControl / PageBarControl / TextEditorControl);PropertyControl 属性编辑器见第六章;property/wpf 子控件全览(ColorPicker / FilePicker / 内置 DataGrid / TreeListBox 等 20+)见 §6.2。
ButtonControl — 图标按钮
xml<snet:ButtonControl Margin="10" HorizontalAlignment="Center" Command="{Binding SaveCommand}" Content="{snet:Loc Save}" Icon="{DynamicResource Save}" />
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Content | string | — | 按钮文本 |
Icon | ImageSource | null | 图标 |
Command | ICommand | null | 绑定命令 |
CornerRadius | CornerRadius | new CornerRadius(5)(v26.250 起由 8 调为 5) | 圆角 |
ComboBoxControl — 下拉选择框
xml<snet:ComboBoxControl Width="200" DisplayMemberPath="Key" Hint="请选择..." Icon="{DynamicResource ScanCode}" ItemsSource="{Binding DeviceList}" SelectedItem="{Binding SelectedDevice}" />
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Hint | object | — | 占位提示文本 |
ItemsSource | IEnumerable | null | 数据源 |
SelectedItem | object | null | 选中项(双向绑定) |
DisplayMemberPath | string | — | 显示路径 |
Icon | ImageSource | null | 图标 |
TextBoxControl — 文本输入框
xml<snet:TextBoxControl Width="200" Hint="请输入名称" ClearButtonEnabled="True" Icon="{DynamicResource Scan}" Text="{Binding SearchText}" />
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Text | object | null | 输入文本(双向绑定) |
Hint | string | — | 占位提示文本 |
ClearButtonEnabled | bool | true | 是否显示清除按钮 |
Icon | ImageSource | null | 图标 |
LedGaugeControl — LED 指示灯
xml<snet:LedGaugeControl Width="30" Height="30" Color="Red" IsOn="{Binding AlarmActive}" IsFlashing="True" FlashingInterval="300" OnLightness="0.8" OffLightness="0.2" />
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Color | Color | Green | LED 颜色 |
IsOn | bool | false | 亮/灭状态 |
IsFlashing | bool | false | 闪烁模式 |
FlashingInterval | double | 500 | 闪烁间隔(毫秒) |
OnLightness | double | 0.5 | 点亮时的亮度 |
OffLightness | double | 0.3 | 熄灭时的亮度 |
IsFlat | bool | false | 扁平模式(移除外阴影) |
PageBarControl — 分页栏
xml<snet:PageBarControl PageIndex="{Binding PageIndex, Mode=TwoWay}" PageSize="{Binding PageSize, Mode=TwoWay}" Total="{Binding TotalCount, Mode=TwoWay}" MaxDisplayedPageCount="7" />
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
PageIndex | int | 1 | 当前页码(1-based) |
PageSize | int | — | 每页条数 |
Total | int | — | 总条目数 |
MaxDisplayedPageCount | int | 7 | 最大显示页码数 |
csharp// ViewModel 中处理分页变更 partial class MainViewModel : BindNotify { public int PageIndex { get => GetProperty(() => PageIndex); set => SetProperty(() => PageIndex, value); } public int PageSize { get => GetProperty(() => PageSize); set => SetProperty(() => PageSize, value); } public int Total { get => GetProperty(() => Total); set => SetProperty(() => Total, value); } // 页码变化命令 public ICommand PageChangedCommand => new RelayCommand<int>(async (page) => { await LoadPageAsync(page); }); }
编辑控件 — TextEditor / TextEditorControl(代码编辑器)
v26.222.1 起 AvalonEdit 依赖已移除,代码编辑器以源码形式内嵌(命名空间
Snet.Windows.Controls.edit,旧AvalonEdit.*命名空间不再可用):
xml<!-- XAML: xmlns:snet="https://snet.cn" --> <snet:TextEditorControl Height="300" FontFamily="Consolas" />
csharp// 代码方式 using Snet.Windows.Controls.edit; var editor = new TextEditorControl { Height = 300 }; editor.Text = "var x = 1;";
内嵌源码覆盖 AvalonEdit 全套能力:代码高亮(Highlighting)、代码折叠(Folding)、搜索(Search)、自动补全(CodeCompletion)、文档(Document)、代码片段(Snippets)等,
TextEditor实现ITextEditorComponent/IServiceProvider,深浅色主题随应用主题自动适配。
🔧 第六章:PropertyControl 属性编辑器
基础用法
xml<snet:PropertyControl BasicsData="{Binding SettingsObject}" />
配置对象
csharpusing Snet.Windows.Controls.property.core.DataAnnotations; // 注解所在命名空间(非 property.wpf) using System.Windows.Media; // Color / Colors // 属性对象 public class DeviceSettings { [DisplayName("设备名称")] [Category("基本信息")] public string DeviceName { get; set; } = "PLC-001"; [DisplayName("IP 地址")] [Category("连接")] public string IpAddress { get; set; } = "192.168.0.1"; [DisplayName("端口")] [Category("连接")] [Slidable(0, 65535)] public int Port { get; set; } = 6688; [DisplayName("颜色")] [Category("外观")] public Color IndicatorColor { get; set; } = Colors.Green; [DisplayName("启用日志")] [Category("高级")] public bool EnableLog { get; set; } = true; [DisplayName("协议类型")] [Category("连接")] [ItemsSourceProperty("ProtocolTypes")] // ⚠️ 实参是"属性名"字符串,不是 Type! public string ProtocolType { get; set; } public string[] ProtocolTypes => new[] { "Modbus", "Siemens", "OPC UA" }; // 数据源属性 [DisplayName("固件文件")] [Category("高级")] [InputFilePath("hex", "Firmware Files|*.hex;*.bin")] // 第 1 参 = 默认扩展名(无过滤器的简写 [InputFilePath("hex")]) public string FirmwarePath { get; set; } [Browsable(false)] public string InternalId { get; set; } // 不会在界面中显示 }
PropertyGrid 注解一览
| Attribute | 用途 |
|---|---|
[DisplayName] | 显示名称 |
[Category] | 分类分组 |
[Description] | 提示描述 |
[Browsable(false)] | 隐藏属性 |
[ReadOnly(true)] | 只读属性 |
[Editable(false)] | 不可编辑 |
[Slidable(min, max[, smallChange, largeChange])] | 滑块控件 |
[Spinnable(smallChange, largeChange, minimum, maximum)] | 数字微调控件(4 参构造,如 [Spinnable(1, 1, 0, 65535)];无 3 参构造) |
[SelectorStyle(ComboBox)] | 下拉选择样式 |
[ItemsSourceProperty("属性名")] | 数据源(字符串属性名,非 Type;属性返回 IEnumerable) |
[InputFilePath("默认扩展名")] | 文件输入选择器(单参=默认扩展名;两参=扩展名+过滤器) |
[OutputFilePath("默认扩展名")] | 文件输出选择器 |
[DirectoryPath] | 目录选择器 |
[FontFamilySelector] | 字体选择器 |
[Width(width)] | 宽度(单参:宽度值) |
[Height(height, minHeight?, maxHeight?)] | 高度(首参=高度值,后两参可选限制) |
[FormatString("{0:F2}")] | 格式化字符串 |
[Progress] | 进度条显示 |
[CheckableItems] | 可勾选列表 |
[EnableByRadioButton] | 单选框条件启用 |
[VisibleBy("OtherProperty")] | 条件可见 |
[EnableBy("OtherProperty")] | 条件启用 |
[SortIndex(n)] | 排序 |
[HeaderPlacement(Left)] | 标题位置 |
[IndentationLevel(n)] | 缩进层级 |
6.2 property/wpf 内置子控件全览(20+ 个)
来源与命名空间: 以下控件位于
Snet.Windows.Controls.property.wpf(PropertyControl 属性编辑器的内部控件集),snet:前缀(https://snet.cn)可直接使用,也可在 XAML 中独立使用。⚠️ 其中snet:DataGrid、snet:PropertyGrid与System.Windows.Controls中的同名类型不是同一个类,注意区分。
① 独立使用前:先合并样式字典
PropertyControl 在内部已自动合并全部子控件样式;脱离 PropertyControl 单独使用子控件时,必须先手动合并对应 Generic.xaml 字典,否则控件无模板渲染(显示空白):
xml<ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/ColorPicker/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/FilePicker/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/RadioButtonList/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/SpinControl/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/HeaderedEntrySlider/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/CheckMark/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/DockPanelSplitter/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/PopupBox/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/Controls/TextBlockEx/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/PropertyGrid/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/TreeListBox/Generic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Snet.Windows.Controls;component/property/wpf/DataGrid/Generic.xaml" /> </ResourceDictionary.MergedDictionaries>
② 选择 / 输入类
ColorPicker — 颜色选择器(继承 ComboBox,下拉展开色板 / HSV / 光谱)
xml<snet:ColorPicker SelectedColor="{Binding LedColor}" />
| 属性 | 类型 | 说明 |
|---|---|---|
SelectedColor | Color? | 当前选中颜色(双向绑定) |
FilePicker — 文件选择框
xml<snet:FilePicker FilePath="{Binding ConfigPath}" Filter="JSON 文件 (*.json)|*.json|所有文件 (*.*)|*.*" DefaultExtension="json" Multiselect="False" UseOpenDialog="True" />
| 属性 | 说明 |
|---|---|
FilePath | 文件路径(双向绑定) |
Filter | 文件对话框过滤器串(WPF 格式 名称|*.ext|...) |
DefaultExtension | 默认扩展名 |
Multiselect | 是否多选 |
UseOpenDialog | true=打开对话框 / false=保存对话框 |
IsInputEnabled | 是否允许手动输入路径 |
BasePath | 相对路径基准目录 |
BrowseButtonContent / ExploreButtonContent / OpenButtonContent 等 | 按钮内容/提示自定义 |
DirectoryPicker — 目录选择框
xml<snet:DirectoryPicker Directory="{Binding ExportDir}" />
关键属性:Directory(双向绑定)、BrowseButtonContent / ExploreButtonContent。
RadioButtonList — 枚举单选列表
xml<snet:RadioButtonList EnumType="{x:Type local:DeviceType}" Value="{Binding DeviceTypeValue}" Orientation="Horizontal" ItemMargin="4" />
| 属性 | 说明 |
|---|---|
EnumType | 枚举类型 |
Value | 当前选中值(object,双向绑定) |
Orientation / ItemMargin / ItemPadding | 布局 |
DescriptionConverter | 显示文本转换器(如 EnumDescriptionConverter) |
FormattingTextBox — 格式化输入框
xml<snet:FormattingTextBox Value="{Binding DoubleValue}" StringFormat="0.###" />
关键属性:Value(object,双向绑定)、StringFormat、FormatProvider。
SpinControl — 上下微调控件(数字 / 时间)
xml<snet:SpinControl Value="{Binding Port}" Minimum="0" Maximum="65535" SmallChange="1" LargeChange="10" RepeatInterval="100" />
| 属性 | 说明 |
|---|---|
Value / Minimum / Maximum | 值 / 范围(object) |
SmallChange / LargeChange | 步进 / 大步进 |
RepeatInterval | 按住时重复间隔(毫秒) |
SpinButtonWidth | 按钮宽度 |
Culture | 数字格式化区域 |
HeaderedEntrySlider — 标题 + 数值框 + 滑块
xml<snet:HeaderedEntrySlider Header="采样间隔" Value="{Binding Interval}" Minimum="100" Maximum="10000" SmallChange="100" LargeChange="1000" EntryStringFormat="{}{0:F0}" />
关键属性:Header、Value、Minimum / Maximum、SmallChange / LargeChange、HeaderWidth / EntryWidth(GridLength)、EntryStringFormat、EntryContentAlignment。
SliderEx — Slider 的直接子类(默认样式滑块,无新增属性),用于需要 Slider 默认样式的场景。
TextBoxEx — 文本框增强
xml<snet:TextBoxEx Text="{Binding Code}" SelectAllOnFocus="True" MoveFocusOnEnter="True" UpdateBindingOnEnter="True" />
| 属性 | 说明 |
|---|---|
SelectAllOnFocus | 获得焦点时全选 |
ScrollToHomeOnFocus | 获得焦点时滚动到开头 |
MoveFocusOnEnter | 回车移动焦点 |
UpdateBindingOnEnter | 回车时提交绑定 |
TextBlockEx — TextBlock 的直接子类(默认样式,无新增属性)。
EditableTextBlock — 可编辑文本块(TextBlock + 编辑态切换)
xml<snet:EditableTextBlock Text="双击可编辑" IsEditing="{Binding IsEditing}" />
关键属性:IsEditing(是否编辑态)、HorizontalContentAlignment / VerticalContentAlignment。
CheckMark — 对勾标记
xml<snet:CheckMark IsChecked="True" />
关键属性:IsChecked(bool)。
EnumMenuItem — 枚举菜单项(继承 MenuItem)
xml<snet:EnumMenuItem Header="设备级别" SelectedValue="{Binding Level}" />
关键属性:SelectedValue(object,双向绑定)。
③ 容器 / 布局类
DockPanelSplitter — 分隔条(DockPanel 子项之间拖动调宽)
xml<DockPanel> <snet:DockPanelSplitter DockPanel.Dock="Right" Thickness="4" /> <Border>…</Border> </DockPanel>
关键属性:Thickness(分隔条厚度)、IsHorizontal、ProportionalResize(按比例缩放两侧)。
StackPanelEx — 限高 StackPanel(超出 VisibleChildrenCount 的子项自动 Collapsed)
xml<snet:StackPanelEx VisibleChildrenCount="5"> <!-- 第 6 项起自动隐藏 --> </snet:StackPanelEx>
PopupBox — 弹出模板下拉(继承 ComboBox,下拉显示自定义 DataTemplate)
xml<snet:PopupBox> <snet:PopupBox.PopupTemplate> <DataTemplate> <StackPanel> <snet:TextBlockEx Text="自定义弹层内容" /> <snet:ButtonControl Content="确定" /> </StackPanel> </DataTemplate> </snet:PopupBox.PopupTemplate> </snet:PopupBox>
LinkBlock — 超链接文本(点击用系统浏览器打开)
xml<snet:LinkBlock Text="访问官网" NavigateUri="https://shunnet.top" />
PropertyGrid — 属性网格(独立使用版,不套窗口/滚动条)
xml<snet:PropertyGrid SelectedObject="{Binding SettingsObject}" ShowReadOnlyProperties="True" />
| 属性 | 说明 |
|---|---|
SelectedObject / SelectedObjects | 编辑对象(单个 / 多个) |
ShowReadOnlyProperties | 是否显示只读属性 |
EnumAsRadioButtonsLimit | 枚举项数 ≤ 该值时用单选按钮显示 |
LabelWidthSharing / EnableLabelWidthResizing | 标签列宽共享 / 可拖拽调整 |
TabVisibility / TabStripPlacement | 分类页签显示与位置 |
CategoryControlType / CategoryHeaderTemplate | 分类样式 |
ShowDescriptionIcons / DescriptionIcon | 描述图标 |
Indentation / VerticalPropertySpacing | 缩进 / 行距 |
日常使用推荐
snet:PropertyControl包装(含标题栏/滚动/按钮,见 §6.1);需要裸网格时用snet:PropertyGrid。
DataGrid(property/wpf 内置版) — ⚠️ 与 System.Windows.Controls.DataGrid 完全不同的另一个表格控件(命名空间 Snet.Windows.Controls.property.wpf,PropertyControl 内部表格),ItemsSource 类型为 IList:
xml<snet:DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="True" CanInsert="True" CanDelete="True" />
| 属性 | 说明 |
|---|---|
ItemsSource | IList(非 IEnumerable) |
AutoGenerateColumns / ColumnDefinitions | 自动/手动列定义 |
AutoInsert / CreateItem | 自动插入新行 / 行工厂 |
CanInsert / CanDelete / CanCopy / CanCut / CanPaste / CanClear | 编辑能力开关 |
IsAutoFillEnabled / AutoFillCell | 拖拽自动填充 |
ClipboardSeparator | 剪贴板分隔符 |
CurrentCell / CustomSort / InputDirection | 当前单元格 / 排序 / 输入方向 |
RowHeadersSource / ColumnHeadersSource / GridLineBrush / HeaderBorderBrush | 表头/网格线外观 |
Operator | IDataGridOperator 数据操作器 |
TreeListBox — 树形列表(支持拖拽、多选、展开路径绑定)
xml<snet:TreeListBox HierarchySource="{Binding Tree}" ChildrenPath="Children" IsExpandedPath="IsExpanded" />
关键属性:HierarchySource(根集合)、ChildrenPath(子节点属性名)、IsExpandedPath / IsSelectedPath、Indentation。
④ 对话框
PropertyDialog — 属性编辑对话框(窗口内嵌 PropertyGrid + OK/Apply/Cancel)
csharpusing Snet.Windows.Controls.property.wpf; var dialog = new PropertyDialog { Owner = Application.Current.MainWindow }; dialog.DataContext = new MySettings(); // 任意对象,属性注解(§6.1)驱动编辑 dialog.ShowDialog();
WizardDialog — 向导对话框(上一步/下一步/完成)
csharpvar wizard = new WizardDialog { Owner = Application.Current.MainWindow }; wizard.Pages = new List<object> { new Step1ViewModel(), new Step2ViewModel() }; wizard.ShowDialog();
关键属性:Pages(List<object>,每页一个对象,页签由对象驱动)、CurrentPage(当前页索引)。
⑤ 数据 / 工具类
ItemsBag — 动态属性包(把多个对象的同名属性合并到一个可编辑对象,用于 PropertyGrid 批量编辑)
csharpusing Snet.Windows.Controls.property.wpf; var bag = new ItemsBag(new object[] { objA, objB }); PropertyControl.BasicsData = bag; // 或 PropertyGrid.SelectedObject = bag bag.Dispose(); // 用完释放
配套数据模型(Snet.Windows.Controls.data):
| 模型 | 用途 |
|---|---|
ComboBoxModel(Key/Value) | 下拉框键值项(DisplayMemberPath="Key") |
EditModel(Name/Description/Color) | 日志标签着色模型(正则标签→颜色) |
ItemsControlModel(Key/…) | 勾选列表项(配合 ItemsControlHandler.GetCheckedItem/SetCheckedItem) |
TabControlModel | 页签模型 |
配套 handler 工具类(Snet.Windows.Controls.handler):
| 类 | 用途 |
|---|---|
Win32Handler.Select | 原生文件/目录选择对话框(§18) |
WpfUiHandler.CreationControl | NavigationView 导航项创建(§14) |
EditBindingHandler.EditText | TextEditor 双向绑定附加属性(§28) |
EditHandler | TextEditor 关键词着色(SetKeywords)+ 代码补全(Complete)+ 主题(SetTheme) |
ItemsControlHandler | GetCheckedItem / SetCheckedItem 勾选扩展 |
UiMessageHandler | 消息队列显示(StartAsync(intervalMs = 200, maxLength = 10000, maxBatchCount = 1000, CancellationToken)——v26.250 起默认间隔 100→200 且新增取消令牌参数;ShowAsync / ClearAsync) |
SettingsHandler | AutoStart(开机自启)/ IsRunAsAdmin / RestartAsAdmin / CreateDesktopShortcut / DeleteDesktopShortcut |
🖱️ 第七章:拖拽控件
DragControlsBase — 缩放+移动
csharpusing Snet.Windows.Controls.drag; // 创建可拖拽的控件(v26.250 起第 5 参 Rotate 可选:启用顶部旋转圈) var dragControl = new DragControlsBase( Controls: targetElement, // 被装饰的 UI 元素 LlayoutContainer: parentGrid, // 父布局容器 Move: true, // 启用拖拽移动 DragSize: true, // 启用 8 向缩放手柄 Rotate: false // 可选:启用旋转功能 ); // 自定义样式 dragControl.BorderColor = new SolidColorBrush(Colors.DodgerBlue); dragControl.ThumbInnerColor = new SolidColorBrush(Colors.White); dragControl.ThumbOuterColor = new SolidColorBrush(Colors.DodgerBlue); dragControl.MinWidths = 50; dragControl.MaxWidths = 800; // v26.250 新增外观/旋转 API: dragControl.SurroundInnerColor = new SolidColorBrush(Color.FromRgb(0x21, 0x96, 0xF3)); dragControl.SurroundOuterColor = new SolidColorBrush(Color.FromRgb(0x90, 0xCA, 0xF9)); dragControl.SetRotation(45); // 编程式设置旋转角度(Angle 属性只读) // dragControl.InitCentreThumb(); // 初始化中心移动圈 // dragControl.InitRotateThumb(); // 初始化顶部旋转圈 // dragControl.Detach(); // 退订移动事件(DragControlsHelper.Remove 会调用) // 将装饰器层应用到目标元素 var adornerLayer = AdornerLayer.GetAdornerLayer(targetElement); adornerLayer.Add(dragControl);
DragControlsAnimate — 拖拽创建新控件
csharpvar dragAnimate = new DragControlsAnimate( Windows: this, // 包含窗口 LlayoutContainer: canvas, // 画布或网格 HeightOffset: 0, WidthOffset: 0 ); // 或 v26.250 新增重载:构造时传入拖拉源集合 // var dragAnimate = new DragControlsAnimate(this, canvas, new[] { sourceControl }, HeightOffset: 0, WidthOffset: 0); // dragAnimate.Initialize(new[] { sourceControl }); // 运行期设置/追加拖拉源 // 注册拖拉源控件(可多次;或用 RegisterSource(sourceName, element)/CreateBySourceName/ContainsSourceName 按名字管理) dragAnimate.RegisterSource("myName", sourceControl); // 拖拽回调 — 返回新控件实例(v26.250 起元组含 IsRotate 第 4 项;字段名 DragEvenTrigger 大写 D;委托要求一个 FrameworkElement 参数) dragAnimate.DragEvenTrigger = (showControl) => { var copy = new Snet.Windows.Controls.button.ButtonControl { Content = "新控件" }; return (copy, IsMove: true, IsDragSize: true, IsRotate: false); }; // 消息回调 — 拖拽过程中传递提示消息(string, FrameworkElement) dragAnimate.MessageEvenTrigger = (message, element) => Console.WriteLine($"[拖拽] {message}"); // v26.250 新增:复制/旋转/上下文菜单 API // 程序创建一个独立副本;不要引用回调内部的局部变量。 var newControl = dragAnimate.CreateBySourceName("myName") ?? throw new InvalidOperationException("拖拉源未注册"); canvas.Children.Add(newControl); dragAnimate.EnableContextMenu = true; // 启用右键菜单(默认 true) dragAnimate.AttachCopyMenu(newControl); // 附加复制菜单 dragAnimate.PinCopy(newControl); // 固定复制项 dragAnimate.UnpinCopy(newControl); dragAnimate.SetRotation(newControl, 90); // 旋转复制项(GetRotation 读取) dragAnimate.ExtractCopy(newControl); // 摘出复制项 dragAnimate.RemoveCopy(newControl); dragAnimate.SettingsRequested += (copy) => { }; // 设置请求事件 DragControlsAnimate.SetSourceName(newControl, "myName"); // 附加属性:SourceName/SN/ExtensionData(静态 Get/Set) // 移除拖拉源 dragAnimate.Remove(sourceControl);
补充:
DragControlsExcessiveAnimate是独立实现,不能假定拥有DragControlsAnimate的全部新行为。DragControlsBase构造参数序为(Controls, LlayoutContainer, Move, DragSize, Rotate = false);DragControlsHelper.Insert(uiElement, container, move, dragSize, rotate = false)与Find(uiElement)管理装饰器。当前 Animate 支持 Canvas.Left/Top 与 Grid.Margin;旋转后按局部轴缩放并固定对角锚点,尺寸约束 100..500,注意鼠标捕获释放。默认通过构造函数创建 UserControl 的独立内容树,不迁移原 UIElement;复制 IsOn/IsFlat/OffLightness 等标量。保留 TextBox 原生编辑菜单,手柄操作菜单单独管理。DragControlsBase.SetRotation(double)是公共入口;Animate.Detach 只解绑语言监听,不等于完整注销全部拖拽源,仍需 Remove(source)。
DragControlsLayout — 布局持久化模型
DragControlsLayout 是可直接交给 System.Text.Json 的画布布局模型;Version 默认 1,Items 默认空集合。每个 DragControlsLayoutItem 保存 Type、X、Y、Width、Height、Angle,并可选保存 Text、IsChecked、Fill、SourceName、SN、ExtensionData 与自定义 Extra 字典:
csharpusing System.Text.Json; using Snet.Windows.Controls.drag; var layout = new DragControlsLayout { Items = [ new DragControlsLayoutItem { Type = "Button", X = 40, Y = 24, Width = 120, Height = 36, Angle = 15, Text = "启动", SourceName = "command-button" } ] }; string json = JsonSerializer.Serialize(layout); var restored = JsonSerializer.Deserialize<DragControlsLayout>(json);
NaturalStringComparer — 自然字符串排序
Snet.Windows.Controls.property.wpf.NaturalStringComparer 实现 IComparer<string?>,按数字片段比较且不受 Int32 上限约束,适合属性网格中的 Item2 / Item10 排序:
csharpusing Snet.Windows.Controls.property.wpf; var names = new[] { "Item10", "Item2", "Item1" }; Array.Sort(names, new NaturalStringComparer());
💬 第八章:消息对话框
Snet.Windows.Core.handler — DialogHandler
DialogHandler 是自定义对话框的公共入口;消息框及拖拽控件的设置对话框也经由此入口。必须先显示 WindowBase;同一窗口里的请求共用按调用顺序处理的异步队列,不同窗口可同时显示。
| API | 默认值 / 契约 |
|---|---|
Task<object?> ShowAsync(object content, DependencyObject? element = null, CancellationToken cancellationToken = default) | content 必须非 null;UIElement 必须在应用 UI 线程创建 |
Task<object?> ShowAsync(Func<object> contentFactory, DependencyObject? element = null, CancellationToken cancellationToken = default) | 工厂在轮到显示时才在应用 UI 线程执行;工厂异常仅使本调用失败并释放队列 |
WindowBase.DialogHostIdentifier | 只读依赖属性;当前窗口主宿主标识符,不能缓存 |
WindowBase.DialogHostClickCloseIdentifier | 只读依赖属性;主标识符加 _ClickClose,用于可点击空白关闭的第二宿主 |
static string WindowBase.GetDialogHostIdentifier(DependencyObject? element = null) | UI 线程调用;解析元素所属 WindowBase,否则活动窗口,再回退最早已加载可见窗口;无已加载 WindowBase 时返回 DialogHost |
element 属于 WindowBase 时选该窗口;否则选活动窗口,再回退已加载的主窗口。每个窗口具有唯一宿主名,传统名称 DialogHost/DialogHost_ClickClose 分配给最早创建且已加载可见的窗口(均隐藏时选最早已加载窗口),关闭/隐藏时移交;传统宿主仍打开对话框时暂不移交。DialogHandler 使用主宿主,不提供点击空白关闭宿主的队列入口。
两种 ShowAsync 均可从后台调用,始终以 DispatcherPriority.Loaded 调度;传入的 element 必须属于应用 UI 线程。工厂重载可安全地延迟创建 UI 内容。禁止把 async () => ... 作为内容工厂:它会绑定到 object 重载并以 ArgumentException 拒绝;先 await 异步数据,再传同步 Func<object>。null 参数同步抛 ArgumentNullException;没有 Application.Current、指定窗口到达 UI 线程时已关闭或尚未加载,以及无可用宿主时抛 InvalidOperationException。
返回值为关闭命令/DialogHost.Close 的参数;未传参数,或通过初始检查后窗口在显示/排队期间关闭,返回 null。窗口重套模板时当前显示调用返回 null,排队请求可继续使用新宿主。到达 UI 线程前已关闭的窗口直接失败,不借用其它窗口宿主。取消令牌只取消排队等待;对话框已经显示后取消不会关闭它。队列没有上限,业务层应避免无限入队;不要在一个对话框的事件中等待排在它后面的对话框。
没有已加载 WindowBase 时,仅回退应用已经提供的 DialogHost 标识符宿主,不创建宿主,也不排队、不跟踪宿主生命周期。直接使用 DialogHost.Show 绕开队列,和队列混用仍可能抛 DialogHost is already open;同时存在同名宿主仍会报 Multiple viable DialogHosts。
下面的方法可放入 WPF 项目;调用前 owner 已 Show(),主题沿用 WindowBase。关闭使用按钮命令,避免假设 ButtonControl 有 Click 或 CommandParameter:
csharpusing CommunityToolkit.Mvvm.Input; using MaterialDesignThemes.Wpf; using Snet.Windows.Controls.button; using Snet.Windows.Core; using Snet.Windows.Core.handler; using System.Threading; using System.Threading.Tasks; public static class DialogExample { public static async Task<bool> ConfirmAsync(WindowBase owner, CancellationToken cancellationToken = default) { object? result = await DialogHandler.ShowAsync( () => new ButtonControl { Content = "Continue", Command = new RelayCommand(() => DialogHost.Close(WindowBase.GetDialogHostIdentifier(owner), true)) }, owner, cancellationToken); return result is true; } }
消息框新增完整 owner 重载:Task<bool> Show(string content, string title, MessageBoxButton btn, MessageBoxImage img, System.Windows.Window? owner)。原有五个重载保留,默认 OK/Information。owner 为 WindowBase 时显示在它的主宿主;null/普通 Window 回退当前活动 WindowBase。消息框与自定义对话框共用队列,不能取消;关闭/换模板返回 false;初始不可用宿主仍抛 InvalidOperationException。每次创建独立内容控件,不会在并行窗口之间复用视觉树。不要新建同名 Host 作为失败回退。
四种按钮模式
csharpusing Snet.Windows.Controls.message; using Snet.Windows.Controls.@enum; // ⚠️ 注意:WPF 项目通常有 `using System.Windows;`,`MessageBox`/`MessageBoxButton`/`MessageBoxImage` // 会与 System.Windows 的同名类型产生歧义(CS0104)。建议使用别名: // using SnetMessageBox = Snet.Windows.Controls.message.MessageBox; // using SnetMessageBoxButton = Snet.Windows.Controls.@enum.MessageBoxButton; // using SnetMessageBoxImage = Snet.Windows.Controls.@enum.MessageBoxImage; // 以下示例省略别名写法,实际代码请按上述别名(或全限定名)使用。 // OK — 仅确认 bool ok = await MessageBox.Show("操作成功", "提示"); // OK Cancel — 确认/取消 bool confirmed = await MessageBox.Show( "确定要删除吗?", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Warning); // Yes — 仅是(返回 true) bool yes = await MessageBox.Show("是否继续?", "提示", MessageBoxButton.Yes, MessageBoxImage.Question); // Yes No — 是/否 bool yesNo = await MessageBox.Show("是否保存?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
| 按钮枚举 | 显示按钮 | 返回 |
|---|---|---|
MessageBoxButton.OK | 确定 | true |
MessageBoxButton.OKCancel | 确定 / 取消 | true / false |
MessageBoxButton.Yes | 是 | true |
MessageBoxButton.YesNo | 是 / 否 | true / false |
| 图标枚举 | 图标类型 |
|---|---|
MessageBoxImage.Information | 信息 |
MessageBoxImage.Warning | 警告 |
MessageBoxImage.Error | 错误 |
MessageBoxImage.Question | 询问 |
🔔 第九章:系统托盘
NotifyIcon 托盘图标
NotifyIcon 是 XAML 元素(继承 FrameworkElement),在 XAML 中声明,代码中注册事件。
MainWindow.xaml:
xml<snet:NotifyIcon x:Name="TrayIcon" FocusOnLeftClick="True" Icon="/icon.ico" LeftClick="TrayIcon_LeftClick" MenuOnRightClick="False" TooltipText="我的应用"> </snet:NotifyIcon>
MainWindow.xaml.cs:
csharpusing System.Windows; using Snet.Windows.Controls.tray.Controls; // 左键点击恢复窗口 private void TrayIcon_LeftClick(NotifyIcon sender, RoutedEventArgs e) { this.Show(); this.WindowState = WindowState.Normal; this.Activate(); } // 窗口关闭时隐藏到托盘(而非退出) protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (!_isExiting) { e.Cancel = true; // 取消关闭 this.Hide(); // 隐藏到托盘 } base.OnClosing(e); } // 由主窗口中的退出按钮命令调用(不生成原生托盘菜单) private void OnExitApp(object sender, RoutedEventArgs e) { _isExiting = true; TrayIcon.Unregister(); // 注销托盘图标 Application.Current.Shutdown(); }
说明:
NotifyIcon提供Register()/Unregister()方法(XAML 声明后通常无需手动调用)和LeftClick/RightClick/LeftDoubleClick等 6 个点击事件,以及TooltipText/Icon/Menu/FocusOnLeftClick/MenuOnRightClick依赖属性。TrayManager是 internal 静态类,用户代码不可直接访问。
当前托盘 TooltipText 使用 Unicode 原生字段,修改后即时刷新,无需重注册。WindowBase.Foreground 使用动态主题资源,切换主题时跟随更新;自定义值覆盖后需自行管理。
代码方式(无 XAML): 也可用
Snet.Windows.Controls.tray.NotifyIconService以纯代码注册托盘图标(设置Icon/TooltipText/ContextMenu后调用Register(),退出时Unregister()+Dispose())。
🧬 第十章:完整示例 — 数采监控面板
下面是一个完整的 WPF 监控面板示例,结合了窗口基类、MVVM、多语言、PropertyGrid、LED 指示灯、分页等:
MainViewModel.cs
csharpusing CommunityToolkit.Mvvm.Input; using Snet.Windows.Core.mvvm; using System.Collections.ObjectModel; using Snet.Windows.Controls.property.core.DataAnnotations; using System.Windows.Media; namespace MyApp; public partial class MonitorViewModel : BindNotify { // 属性通过表达式访问 public string DeviceName => GetProperty(() => DeviceName); public bool IsConnected => GetProperty(() => IsConnected); public int PageIndex { get => GetProperty(() => PageIndex); set => SetProperty(() => PageIndex, value); } public int PageSize { get => GetProperty(() => PageSize); set => SetProperty(() => PageSize, value); } public int Total { get => GetProperty(() => Total); set => SetProperty(() => Total, value); } public Color LedColor => GetProperty(() => LedColor); public ObservableCollection<DeviceModel> Devices { get; } = new(); public DeviceSettings Settings => GetProperty(() => Settings); // 初始化 public MonitorViewModel() { SetProperty(() => DeviceName, "S7-1200-01"); SetProperty(() => PageSize, 20); SetProperty(() => LedColor, Colors.Green); SetProperty(() => Settings, new DeviceSettings()); } // 连接命令 [RelayCommand] private async Task ConnectAsync() { SetProperty(() => IsConnected, true, old => { SetProperty(() => LedColor, Colors.Red); }); await LoadDataAsync(); } // 断开命令 [RelayCommand] private void Disconnect() { SetProperty(() => IsConnected, false); SetProperty(() => LedColor, Colors.Gray); } // 搜索命令 [RelayCommand] private async Task SearchAsync(string keyword) { SetProperty(() => PageIndex, 1); await LoadDataAsync(keyword); } private async Task LoadDataAsync(string? keyword = null) { // 模拟数据加载 await Task.Delay(500); Devices.Clear(); for (int i = 0; i < PageSize; i++) Devices.Add(new DeviceModel { Id = i + 1, Name = $"点位 {i + 1}" }); SetProperty(() => Total, 200); } } public class DeviceModel { public int Id { get; set; } public string Name { get; set; } = ""; } public class DeviceSettings { [DisplayName("设备名称")] [Category("基本信息")] public string Name { get; set; } = "PLC-001"; [DisplayName("IP 地址")] [Category("连接")] public string Ip { get; set; } = "192.168.0.1"; [DisplayName("端口")] [Category("连接")] [Spinnable(1, 1, 0, 65535)] // 4 参构造(smallChange, largeChange, minimum, maximum) public int Port { get; set; } = 502; [DisplayName("采样间隔")] [Category("采集")] [Slidable(100, 10000)] public int Interval { get; set; } = 1000; }
MainWindow.xaml
xml<snet:WindowBase x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" xmlns:local="clr-namespace:MyApp" Title="{snet:Loc AppTitle}" snet:ResxLocalizationProvider.DefaultAssembly="MyApp" snet:ResxLocalizationProvider.DefaultDictionary="Language" LanguageEnabled="True" SkinEnabled="True" Icon="/Icon.ico" WindowStartupLocation="CenterScreen" Height="700" Width="1100"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition /> <RowDefinition Height="auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="300" /> </Grid.ColumnDefinitions> <!-- 顶部工具栏 --> <StackPanel Grid.Row="0" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,0,0,10"> <!-- 连接状态 LED --> <snet:LedGaugeControl Width="24" Height="24" Color="{Binding LedColor}" IsOn="{Binding IsConnected}" VerticalAlignment="Center" Margin="5" /> <snet:TextBlockEx Text="{Binding DeviceName}" FontSize="16" VerticalAlignment="Center" Margin="10,0" /> <snet:ButtonControl Content="{snet:Loc Connect}" Command="{Binding ConnectCommand}" Icon="{DynamicResource Connect}" Margin="5" /> <snet:ButtonControl Content="{snet:Loc Disconnect}" Command="{Binding DisconnectCommand}" Icon="{DynamicResource Disconnect}" Margin="5" /> <snet:TextBoxEx Width="200" Margin="20,0,0,0" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"> <b:Interaction.Triggers> <b:EventTrigger EventName="TextChanged"> <b:InvokeCommandAction Command="{Binding SearchCommand}" CommandParameter="{Binding Text, RelativeSource={RelativeSource AncestorType=snet:TextBoxEx}}" /> </b:EventTrigger> </b:Interaction.Triggers> </snet:TextBoxEx> </StackPanel> <!-- 数据表格 --> <snet:DataGrid Grid.Row="1" Grid.Column="0" ItemsSource="{Binding Devices}" AutoGenerateColumns="True" Margin="0,0,10,0" /> <!-- 右侧属性面板 --> <Border Grid.Row="1" Grid.Column="1" BorderBrush="{DynamicResource MaterialDesignBody}" BorderThickness="1" CornerRadius="4"> <snet:PropertyControl BasicsData="{Binding Settings}" /> </Border> <!-- 底部分页栏 --> <snet:PageBarControl Grid.Row="2" Grid.ColumnSpan="2" PageIndex="{Binding PageIndex, Mode=TwoWay}" PageSize="{Binding PageSize, Mode=TwoWay}" Total="{Binding Total, Mode=TwoWay}" MaxDisplayedPageCount="7" Margin="0,10,0,0" /> </Grid> </snet:WindowBase>
📐 第十一章:XAML 命名空间与资源
XML 命名空间
xmlxmlns:snet="https://snet.cn"
控件命名空间映射
| 前缀 | 命名空间 | 程序集 |
|---|---|---|
snet: | Snet.Windows.Core 和 Snet.Windows.Controls | 两程序集共享同一 XMLNS |
内置图标资源
库内置图标 key 存于 Snet.Windows.Core/resources/Icons.xaml(150+ 个),常用真实 key(DynamicResource 引用,拼错会静默无图标):
xmlIcon="{DynamicResource Save}" Icon="{DynamicResource Connect}" Icon="{DynamicResource Scan}" Icon="{DynamicResource ScanCode}" Icon="{DynamicResource AutoHandler}" Icon="{DynamicResource Send}"
⚠️ 注意: 不存在
Hello/SaveIcon/SearchIcon/DeviceIcon/ConnectIcon/DisconnectIcon等 key(旧版文档杜撰)。示例中使用自定义 key 需自行在资源字典定义。
自定义图标加载:
csharp// 从外部 ResourceDictionary 文件加载 IconsHandler.Loading("pack://application:,,,/MyApp;component/Resources/Icons.xaml"); // 获取图标(key 不存在抛 KeyNotFoundException) var icon = IconsHandler.GetIcon("MyCustomIcon");
常用 DynamicResource Key
| Key | 说明 |
|---|---|
WindowBackgroundBrush | 窗口背景 |
MaterialDesignBody | 文本/边框色 |
UiScrollBar | 滚动条样式 |
DefaultComboBoxStyle | 下拉框默认样式 |
DefaultComboBoxItemStyle | 下拉框项样式 |
MaterialDesignRaisedButton | 凸起按钮样式 |
MaterialDesignFlatButton | 扁平按钮样式 |
MaterialDesignCircularProgressBar | 圆形进度条 |
⚙️ 第十二章:自定义控件开发
创建自定义 UserControl
csharp// MyCustomControl.xaml.cs using Snet.Windows.Core.mvvm; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MyApp.Controls; public partial class MyCustomControl : UserControl { public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(nameof(Header), typeof(string), typeof(MyCustomControl), new PropertyMetadata("")); public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(double), typeof(MyCustomControl), new PropertyMetadata(0.0)); public string Header { get => (string)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); } public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } public MyCustomControl() { InitializeComponent(); } }
继承 BindNotify 创建 ViewModel
csharppublic class MyControlViewModel : BindNotify { public int Count => GetProperty(() => Count); [RelayCommand] private void Increment() { SetProperty(() => Count, Count + 1); } }
📋 第十三章:常见问题排查
| 问题 | 原因 | 解决 |
|---|---|---|
| 窗口最大化有白色边框 | GlassFrameThickness 溢出 | 无需处理——WindowBase 在 SourceInitialized 时基于系统边框指标与 DPI 自动计算 MaximizeBorderThickness 并覆盖手动赋值 |
| 皮肤切换后图标不变色 | 图标未使用 DynamicResource | 使用 {DynamicResource ImageColor} 作为图标颜色 |
| 语言切换后文本不刷新 | 绑定未使用 LocExtension | 使用 {snet:Loc Key} 代替硬编码文本 |
| 拖拽控件位置漂移 | 容器坐标系或旋转缩放锚点不匹配 | Canvas 使用 Left/Top,Grid 使用 Margin;检查局部轴及鼠标捕获生命周期 |
| LED 闪烁不流畅 | 闪烁间隔过短 | 建议 FlashingInterval >= 200 |
| 属性编辑器中属性不显示 | 缺少 public get/set | 确保属性有 public getter 和 setter |
🧭 第十四章:NavigationView 导航壳模式
基于 WPF-UI 的 NavigationView 控件,构建带侧边导航的多页签桌面应用壳。
基础布局
xml<snet:WindowBase x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" Title="{snet:Loc SystemTitle}" Height="900" Width="1600" Icon="/icon.ico"> <Grid> <wpfui:NavigationView x:Name="NavigationViewControls" FooterMenuItemsSource="{Binding FooterMenuItemsSource}" IsBackButtonVisible="Auto" IsPaneToggleVisible="True" MenuItemsSource="{Binding MenuItemsSource}" OpenPaneLength="260" /> </Grid> </snet:WindowBase>
MainWindowViewModel — 菜单数据源
csharpusing Snet.Windows.Core.mvvm; using Snet.Windows.Controls.handler; using Wpf.Ui.Controls; using System.Collections.ObjectModel; public class MainWindowViewModel : BindNotify { public ICollection<object> MenuItemsSource { get => GetProperty(() => MenuItemsSource); set => SetProperty(() => MenuItemsSource, value); } public ICollection<object> FooterMenuItemsSource { get => GetProperty(() => FooterMenuItemsSource); set => SetProperty(() => FooterMenuItemsSource, value); } public MainWindowViewModel() { MenuItemsSource = new ObservableCollection<object> { new NavigationViewItem() { NavigationCacheMode = NavigationCacheMode.Required, Content = "Daq", Icon = new SymbolIcon { Symbol = SymbolRegular.CatchUp24 }, MenuItemsSource = new object[] { WpfUiHandler.CreationControl( "西门子", SymbolRegular.Molecule28, typeof(SiemensView), true, App.LanguageOperate), WpfUiHandler.CreationControl( "Modbus", SymbolRegular.Molecule28, typeof(ModbusView), true, App.LanguageOperate), // ... 更多协议页 ... } }, new NavigationViewItem() { NavigationCacheMode = NavigationCacheMode.Required, Content = "Mq", Icon = new SymbolIcon { Symbol = SymbolRegular.Flowchart24 }, MenuItemsSource = new object[] { WpfUiHandler.CreationControl( "Mqtt", SymbolRegular.PlayMultiple16, typeof(MqttClientView), true, App.LanguageOperate), // ... } }, new NavigationViewItem() { NavigationCacheMode = NavigationCacheMode.Required, Content = "通信", Icon = new SymbolIcon { Symbol = SymbolRegular.Communication16 }, MenuItemsSource = new object[] { WpfUiHandler.CreationControl( "Tcp", SymbolRegular.ArrowTrendingSparkle24, typeof(TcpClientView), true, App.LanguageOperate), WpfUiHandler.CreationControl( "Serial", SymbolRegular.ArrowTrendingSparkle24, typeof(SerialView), true, App.LanguageOperate), } }, new NavigationViewItem() { NavigationCacheMode = NavigationCacheMode.Required, Content = "工具", Icon = new SymbolIcon { Symbol = SymbolRegular.Toolbox28 }, MenuItemsSource = new object[] { WpfUiHandler.CreationControl( "Svg", SymbolRegular.SplitVertical20, typeof(SvgView), true, App.LanguageOperate), } }, }; FooterMenuItemsSource = new ObservableCollection<object> { WpfUiHandler.CreationControl( "关于", SymbolRegular.Info28, typeof(AboutView), true, App.LanguageOperate), }; } }
WpfUiHandler.CreationControl 辅助方法
csharp// 位于 Snet.Windows.Controls.handler.WpfUiHandler // 创建带路由的导航项,自动绑定多语言标题 public static NavigationViewItem CreationControl( string name, // 显示名称(多语言 Key) SymbolRegular symbol, // WPF-UI 内置图标 Type type, // 目标 View 类型 bool multilingual, // 是否多语言(第 4 参是 multilingual 非 isNavigationCache) LanguageModel model) // 语言模型
可选搜索框:
xml<wpfui:NavigationView.AutoSuggestBox> <wpfui:AutoSuggestBox x:Name="AutoSuggestBox" PlaceholderText="Search"> <wpfui:AutoSuggestBox.Icon> <wpfui:IconSourceElement> <wpfui:SymbolIconSource Symbol="Search24" /> </wpfui:IconSourceElement> </wpfui:AutoSuggestBox.Icon> </wpfui:AutoSuggestBox> </wpfui:NavigationView.AutoSuggestBox>
🧩 第十五章:模板化视图架构
⚠️ 本章为架构示意(参考实现):
DaqTemplateViewModel<T>/MqTemplateViewModel<T>/CommunicationClientTemplateViewModel<T>等模板 VM 与template/DaqTemplateView.xaml在 Daq 应用当前源码中不存在(旧版架构,Daq 的 viewModel 现为 AddressSettingsModel/ConsoleModel/PluginSettingsModel 等独立类)。下述代码不可直接编译,仅用于理解"DataTemplate + VM 基类"的设计思路;编写 Daq 应用请以实际源码为准。
Daq 大规模使用 DataTemplate + ViewModel 继承链 模式:共享 UI 布局通过 ResourceDictionary 中的 DataTemplate 定义,各协议页面仅需 5 行 XAML + 5 行 C#。
五种内置模板
| 模板 Key | 用途 | 对应 VM 基类 | 主要控件 |
|---|---|---|---|
DAQ | 采集协议调试 | DaqTemplateViewModel<T> | PropertyGrid侧栏 + 数据类型RadioButton + 地址/读/写/订阅 + 三区日志 |
MQ | 消息中间件调试 | MqTemplateViewModel<T> | PropertyGrid侧栏 + Topic/Content + 发布/订阅 + 双区日志 |
CommunicationClient | TCP/WS/Serial 客户端 | CommunicationClientTemplateViewModel<T> | 发送格式(ASCII/HEX) + 数据输入 + 发送 + 单区日志 |
CommunicationService | TCP/WS 服务端 | CommunicationServiceTemplateViewModel<T> | 同上 + 服务端管理 |
MqService | MQ 服务端 | MqServiceTemplateViewModel<T> | 同上 + 服务端管理 |
DAQ 模板 — 采集协议面板结构
┌─ DrawerHost ─────────────────────────────────────────────┐ │ ┌─ 左抽屉: PropertyControl (BasicsData 属性编辑) ────┐ │ │ └────────────────────────────────────────────────────┘ │ │ ┌─ 功能区 ────────────────────────────────────────────┐ │ │ │ 打开 | 关闭 获取对应类型参数 │ │ │ │ ┌─ 数据类型 (20 个 RadioButton) ─────────────────┐ │ │ │ │ │ String | Double | Int | Bool | Byte[] | ... │ │ │ │ │ └───────────────────────────────────────────────┘ │ │ │ │ [地址] [长度] [读取] [订阅] │ │ │ │ [数据] [编码类型▼] [写入] [取消订阅] │ │ │ └────────────────────────────────────────────────────┘ │ │ ┌─ 信息事件 ───────┐ ┌─ 数据事件 ─────────────────────┐ │ │ │ [清空] │ │ [清空] │ │ │ │ (滚动日志框) │ │ (滚动日志框) │ │ │ └──────────────────┘ └────────────────────────────────┘ │ │ ┌─ 交互数据(原始帧收发日志)─────────────────────────┐ │ │ │ [清空] │ │ │ │ (滚动日志框 — 可折叠) │ │ │ └────────────────────────────────────────────────────┘ │ └──────────────────────────────────────────────────────────┘
采集协议 View 示例(SiemensView)
SiemensView.xaml — 仅 23 行:
xml<UserControl x:Class="Daq.view.SiemensView" xmlns:snet="https://snet.cn" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" xmlns:ui="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:vm="clr-namespace:Daq.viewModel" snet:ResxLocalizationProvider.DefaultAssembly="Daq" snet:ResxLocalizationProvider.DefaultDictionary="Language"> <UserControl.Resources> <ResourceDictionary Source= "pack://application:,,,/Daq;component/template/DaqTemplateView.xaml" /> </UserControl.Resources> <UserControl.DataContext> <vm:SiemensViewModel /> </UserControl.DataContext> <wpfui:Card> <wpfui:Card Content="{Binding}" ContentTemplate="{DynamicResource DAQ}" /> </wpfui:Card> </UserControl>
SiemensViewModel.cs — 仅 22 行:
csharpusing Daq.template; using Snet.Siemens; using static Snet.Siemens.SiemensData; namespace Daq.viewModel; public class SiemensViewModel : DaqTemplateViewModel<Basics> { public SiemensViewModel() { BasicsData = new Basics(); FileName = typeof(SiemensData).Name; Daq = SiemensOperate.Instance(BasicsData); GetAutoAllocatingParamVisibility = Daq.ExistsAutoAllocatingParam().Status ? Visibility.Visible : Visibility.Collapsed; Key = Daq.GetArgs()?.GetSource<ParamModel>()?.Name; } }
消息中间件 View 示例(MqttClientViewModel)
csharpusing Daq.template; using Snet.Mqtt.client; using static Snet.Mqtt.client.MqttClientData; namespace Daq.viewModel; public class MqttClientViewModel : MqTemplateViewModel<Basics> { public MqttClientViewModel() { BasicsData = new Basics(); FileName = typeof(MqttClientData).Name; Mq = MqttClientOperate.Instance(BasicsData); Key = Mq.GetArgs()?.GetSource<ParamModel>()?.Name; } }
通信客户端 View 示例(TcpClientViewModel)
csharpusing Daq.template; using Snet.Core.communication.net.tcp.client; using static Snet.Core.communication.net.tcp.client.TcpClientData; namespace Daq.viewModel; public class TcpClientViewModel : CommunicationClientTemplateViewModel<Basics> { public TcpClientViewModel() { BasicsData = new Basics(); FileName = typeof(TcpClientData).Name; Communication = TcpClientOperate.Instance(BasicsData); Key = "TcpClient"; DataFormat = 1; // 1 = HEX, 0 = ASCII } }
ViewModel 继承链总结
BindNotify ├── DaqTemplateViewModel<T> ← 采集协议基类 │ ├── SiemensViewModel │ ├── ModbusViewModel │ ├── OmronViewModel │ ├── OPC UA Client VM │ └── ... (30+ 协议) ├── MqTemplateViewModel<T> ← MQ 客户端基类 │ ├── MqttClientViewModel │ ├── KafkaViewModel │ └── RabbitMQ / NetMQ / Netty VM ├── MqServiceTemplateViewModel<T> ← MQ 服务端基类 │ ├── MqttServiceViewModel │ └── MqttWebSocketServiceViewModel ├── CommunicationClientTemplateViewModel<T> ← 通信客户端基类 │ ├── TcpClientViewModel │ ├── WsClientViewModel │ └── SerialViewModel ├── CommunicationServiceTemplateViewModel<T> ← 通信服务端基类 │ ├── TcpServiceViewModel │ └── WsServiceViewModel └── 独立 ViewModel ├── SvgViewModel ├── GifViewModel ├── AboutViewModel └── ...
🛡️ 第十六章:全局异常处理
WPF 应用中未捕获的异常会导致进程静默退出。需要三层全局捕获:
csharp// App.xaml.cs public partial class App : Application { private void OnStartup(object sender, StartupEventArgs e) { RegisterEvents(); // ... } private void RegisterEvents() { // 第一层:Task 线程内未捕获异常 TaskScheduler.UnobservedTaskException += (sender, e) => { var ex = e.Exception as Exception; if (ex?.HResult == -2146233088) return; // 忽略特定错误码 HandleException(ex); e.SetObserved(); }; // 第二层:UI 主线程未捕获异常 this.DispatcherUnhandledException += (sender, e) => { HandleException(e.Exception); e.Handled = true; // 标记已处理,防止进程退出 }; // 第三层:非 UI 子线程未捕获异常 AppDomain.CurrentDomain.UnhandledException += (sender, e) => { if (e.ExceptionObject is Exception ex) HandleException(ex); }; } private async Task HandleException(Exception e) { // 构建完整错误消息 string msg = $"{e.Source}\r\n{e.Message}\r\n\r\n{e.StackTrace}"; // 弹出错误对话框(⚠️ 需 using Snet.Windows.Controls.message 并用别名避免与 System.Windows.MessageBox 歧义,见 §8) await Application.Current.Dispatcher.InvokeAsync(async () => { await SnetMessageBox.Show(msg, "全局异常捕获", SnetMessageBoxButton.OK, SnetMessageBoxImage.Exclamation); }, DispatcherPriority.Loaded); // 写入本地日志文件(第 2 参为 foldername:支持文件名/子文件夹,PascalCase 自动转小写点分隔; // 默认路径 {BaseDirectory}/logs/{yyyy-MM-dd}/app.log,可用 LogHelper.Set(new LogModel{...}) 自定义) LogHelper.Error(msg, "App.log", e); } }
退出清理
csharpprivate void OnExit(object sender, ExitEventArgs e) { InjectionWpf.ClearService(); GC.SuppressFinalize(this); GC.Collect(); }
📝 第十七章:异步日志流水线
Daq 的生产级日志模式:ConcurrentQueue 入队 + 定时 50ms 批处理刷新 + UI 线程调度 + 10KB 自动裁剪。
日志流水线实现
csharpusing System.Collections.Concurrent; using System.Text; public class LogPipeline { private readonly ConcurrentQueue<string> _logQueue = new(); private CancellationTokenSource? _logCts; /// <summary>启动日志消费循环</summary> /// <param name="flushIntervalMs">刷新间隔(毫秒),默认 50ms</param> public void Start(int flushIntervalMs = 50) { _logCts = new CancellationTokenSource(); var token = _logCts.Token; Task.Run(async () => { while (!token.IsCancellationRequested) { await Task.Delay(flushIntervalMs, token); FlushLogsToUI(); } }, token); } /// <summary>停止日志循环</summary> public void Stop() => _logCts?.Cancel(); /// <summary>入队一条日志</summary> public void Enqueue(string? msg, DateTime timestamp, bool showTime = true) { if (string.IsNullOrWhiteSpace(msg)) return; string log = showTime ? $"{timestamp:yyyy-MM-dd HH:mm:ss.ffffff} {msg}\r\n" : $"{msg}\r\n"; _logQueue.Enqueue(log); } /// <summary>批量刷新到 UI 线程</summary> private void FlushLogsToUI() { if (Application.Current == null) return; StringBuilder sb = new(); while (_logQueue.TryDequeue(out var log)) sb.Append(log); if (sb.Length > 0) { Application.Current.Dispatcher.Invoke(() => { // 超出 10KB 自动清空(防止 UI 卡顿) if (LogText?.Length > 10000) LogText = string.Empty; LogText += sb.ToString(); }); } } /// <summary>绑定到 ViewModel 的日志文本属性</summary> public string LogText { get; set; } }
滚动条自动跟底
配合 EventCommand 让 TextBox 始终显示最新日志:
xml<snet:TextBoxEx Text="{Binding InfoEvent}" AcceptsReturn="True" MoveFocusOnEnter="False" UpdateBindingOnEnter="False" IsReadOnly="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Hidden"> <b:Interaction.Triggers> <b:EventTrigger EventName="TextChanged"> <snet:EventCommand Command="{Binding InfoEventTextChanged}" /> </b:EventTrigger> </b:Interaction.Triggers> </snet:TextBoxEx>
csharp// ViewModel 中:TextChanged 触发 ScrollToEnd // ⚠️ 需 using Snet.Utility;(GetSource<T> 是 object 扩展方法);类型不匹配时 GetSource 返回 null,需判空 public IAsyncRelayCommand InfoEventTextChanged => new AsyncRelayCommand<TextChangedEventArgs>(e => { var tb = e.Source.GetSource<Snet.Windows.Controls.property.wpf.TextBoxEx>(); if (tb == null) return Task.CompletedTask; tb.SelectionStart = tb.Text.Length; tb.ScrollToEnd(); return Task.CompletedTask; });
📂 第十八章:文件对话框
Win32Handler 提供原生 Windows 文件打开/保存/目录选择对话框,支持文件类型过滤。
选择文件
csharpusing Snet.Windows.Controls.handler; // 选择文件(第二参 selectFolder=false 表示选文件,返回 string,取消时返回 string.Empty) var filters = new Dictionary<string, string> { { "JSON 文件 (*.json)", "*.json" }, { "所有文件 (*.*)", "*.*" }, }; string filePath = Win32Handler.Select("请选择文件", selectFolder: false, filters); // 注意:仅单文件选择,不支持多选
选择文件夹
csharpstring folderPath = Win32Handler.Select("请选择文件夹", selectFolder: true);
导入/导出模式示例
csharp// 导出 JSON 配置 public async Task ExportAsync() { string path = Win32Handler.Select("请选择保存目录", selectFolder: true); if (!string.IsNullOrEmpty(path)) { string file = Path.Combine(path, $"Config[{DateTime.Now:yyyyMMddHHmmss}].json"); File.WriteAllText(file, ConfigData.ToJson()); await InfoEventLogShow("导出成功"); } } // 导入 JSON 配置 public async Task ImportAsync() { string? file = Win32Handler.Select("请选择配置文件", false, new() { { "JSON (*.json)", "*.json" } }); if (!string.IsNullOrEmpty(file)) { var data = File.ReadAllText(file).ToJsonEntity<T>(); if (data != null) BasicsData = data; } }
🎬 第十九章:FFmpeg GIF 转换器
GifHandler 基于 FFmpeg 将视频文件转换为高质量 GIF(palettegen + paletteuse 滤镜)。
使用方式
csharpusing Snet.Iot.Debug.handler; // GifHandler 位于 Snet.Iot.Debug 应用项目,非 WpfMUI 库 var gifHandler = GifHandler.Instance(); // 监听输出行(显示 FFmpeg 进度信息) gifHandler.OnResponse = (line) => { Console.WriteLine($"FFmpeg: {line}"); }; // 监听转换结束 gifHandler.OnEnd = (success) => { if (success) Console.WriteLine("GIF 转换完成!"); else Console.WriteLine("转换失败"); }; // 指定 FFmpeg 路径(默认: AppContext.BaseDirectory/lib/ffmpeg/ffmpeg.exe) gifHandler.FFmpegTool = @"C:\Tools\ffmpeg.exe"; // 执行转换 gifHandler.RunConverter("input.mp4", "output.gif");
转换参数
csharp// 内部使用的 FFmpeg 命令(无需手动设置): // ffmpeg -i "input.mp4" -filter_complex // "fps=25,split [a][b];[a] palettegen=stats_mode=diff [p];[b][p] paletteuse=dither=bayer" // -y "output.gif"
🎨 第二十章:SVG 代码转换器
SvgHandler.SvgCodeConverter 将原始 SVG 内容转换为 WPF 兼容的 DrawingImage XAML 代码。
使用方式
csharpusing Snet.Utility; // 输入参数 string name = "MyIcon"; // 图标名称 string annotation = "我的图标"; // 注释 string svgContent = "<svg>...</svg>"; // 原始 SVG string color = "{DynamicResource ImageColor}"; // 颜色绑定 // 转换 if (SvgHandler.SvgCodeConverter(name, annotation, svgContent, out string xamlCode, color)) { // xamlCode 即为可用的 DrawingImage XAML,可直接粘贴到 ResourceDictionary Console.WriteLine(xamlCode); }
完整 SvgView 示例
xml<!-- 参数区 --> <snet:TextBoxControl Hint="名称" Text="{Binding Name}" /> <snet:TextBoxControl Hint="注释" Text="{Binding Annotation}" /> <snet:TextBoxControl Hint="颜色" Text="{Binding Color}" /> <snet:ButtonControl Content="转换" Command="{Binding Transition}" /> <snet:ButtonControl Content="复制" Command="{Binding Copy}" /> <!-- 输入区 --> <snet:TextBoxEx Text="{Binding InputData}" AcceptsReturn="True" MoveFocusOnEnter="False" UpdateBindingOnEnter="False" /> <!-- 输出区 --> <snet:TextBoxEx Text="{Binding OutData}" AcceptsReturn="True" MoveFocusOnEnter="False" UpdateBindingOnEnter="False" IsReadOnly="True" />
🌳 第二十一章:OPC UA 节点浏览数据模型
⚠️ Debug 应用代码,非 WpfMUI 库 API(命名空间
Snet.Iot.Debug.model,源码 F:/Snet/Debug/Snet.Iot.Debug/model/)。用于构建 OPC UA 树形节点浏览器的结构化数据模型。
OpcUaNodeBrowseStructuralBody
csharp// F:/Snet/Debug/Snet.Iot.Debug/model/OpcUaNodeBrowseStructuralBody.cs // 继承 BindNotify(MVVM 属性通知),皮肤切换时按 IconKey 自动刷新图标 public class OpcUaNodeBrowseStructuralBody : BindNotify { public int PageIndex { get; set; } // 分页索引 public bool IsLoading { get; set; } // 加载中 public string IconKey { get; set; } = ""; // 图标资源 key public object Icon { get; set; } // 图标(皮肤切换自动按 IconKey 重取) public string Name { get; set; } // 节点名称 public object NodeID { get; set; } // 节点 ID public string Count { get; set; } // 子节点数量(字符串) public ObservableCollection<OpcUaNodeBrowseStructuralBody> Children { get; set; } = new(); }
OpcUaNodeBrowseMessageStructuralBody
csharp// F:/Snet/Debug/Snet.Iot.Debug/model/OpcUaNodeBrowseMessageStructuralBody.cs // 消息级别的节点数据(继承 BindNotify) public class OpcUaNodeBrowseMessageStructuralBody : BindNotify { public int Index { get; set; } // 序号 public string Name { get; set; } // 名称 public string Address { get; set; } // 地址 public string Value { get; set; } // 值 public string Type { get; set; } // 类型 public string AccessLevel { get; set; } // 访问级别 public string Description { get; set; } // 描述 }
分页扩展(OPC UA ReferenceDescription)
csharp// 对 OPC UA ReferenceDescriptionCollection 进行分页 public static class PageHandler { public static PagedResult<ReferenceDescription> ToPagedResult( this ReferenceDescriptionCollection source, int pageIndex, int pageSize = 25) { int skip = pageIndex * pageSize; var items = skip >= source.Count ? new List<ReferenceDescription>() : source.Skip(skip).Take(pageSize).ToList(); return new PagedResult<ReferenceDescription> { Items = items, TotalCount = source.Count, PageIndex = pageIndex, PageSize = pageSize }; } } // 配合 PageBarControl 实现 OPC UA 节点分页浏览
🏗️ 第二十二章:生产级应用架构实战
综合运用所有章节的技术,构建与 Daq 同级的完整工业物联网桌面应用。
项目结构
MyApp/ ├── App.xaml # 启动入口,加载主题 ├── App.xaml.cs # 全局异常处理 + 图标加载 ├── MainWindow.xaml # NavigationView 壳 ├── MainWindowViewModel.cs # 菜单数据源 ├── Language.resx # 中文默认资源 ├── Language.en.resx # 英文翻译资源 ├── resources/ │ └── icons.xaml # 自定义图标 ├── view/ # View(每个协议/功能一个) │ ├── SiemensView.xaml + .cs │ ├── ModbusView.xaml + .cs │ ├── SvgView.xaml + .cs │ └── ... ├── viewModel/ # ViewModel(对应 View) │ ├── SiemensViewModel.cs │ ├── ModbusViewModel.cs │ ├── SvgViewModel.cs │ └── ... └── data/ # 数据模型 ├── ItemsControlBody.cs └── ...
App.xaml — 启动配置
xml<Application x:Class="MyApp.App" xmlns:wpfui="http://schemas.lepo.co/wpfui/2022/xaml" Exit="OnExit" Startup="OnStartup"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- 深色主题 --> <ResourceDictionary Source= "pack://application:,,,/Snet.Windows.Core;component/themes/DarkTheme.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
App.xaml.cs — 全局配置
csharppublic partial class App : Application { public static readonly LanguageModel LanguageOperate = new( "MyApp", "Language", "MyApp.dll"); private void OnStartup(object sender, StartupEventArgs e) { RegisterEvents(); // 三层全局异常捕捉 IconsHandler.Loading( "pack://application:,,,/MyApp;component/resources/icons.xaml"); InjectionWpf.Window<MainWindow, MainWindowViewModel>(true).Show(); } private void OnExit(object sender, ExitEventArgs e) { InjectionWpf.ClearService(); GC.Collect(); } }
协议页 ViewModel 架构(示意)
⚠️ 示意架构,非可编译示例:
DaqTemplateViewModel<T>类在 Daq 应用当前源码中不存在(见第十五章警示)。下述代码展示的是"IDaq + BasicsData + 命令 + 三区日志"的页面 VM 设计思路,实际开发请以 Daq 源码(viewModel/ 下的 AddressSettingsModel、ConsoleModel 等)为准。
csharp// 示意:协议页 VM 的典型结构(非真实存在的类) public class ProtocolPageViewModel : BindNotify { // === 核心对象 === public IDaq Daq { get; set; } // 采集接口 public BasicsData BasicsData { get; set; } // 协议配置对象(各协议自己的 Basics) public string FileName { get; set; } // 导出文件名 public string Key { get; set; } // 多语言 Key // === 生命周期 === public ProtocolPageViewModel() { LanguageHandler.OnLanguageEventAsync -= OnLanguageChangedAsync; LanguageHandler.OnLanguageEventAsync += OnLanguageChangedAsync; // On → 注册 Info/Data 异步事件 → 推送三区日志 // 导入: 文件选择 → 反序列化 → 重建实例;导出: BasicsData.ToJson() → 写入 } }
ItemsControlBody — 通用列表项数据模型
csharppublic class ItemsControlBody : BindNotify { public string Name { get => GetProperty(() => Name); set => SetProperty(() => Name, value); } public string Description { get => GetProperty(() => Description); set => SetProperty(() => Description, value); } public string Path { get => GetProperty(() => Path); set => SetProperty(() => Path, value); } public bool IsSelected { get => GetProperty(() => IsSelected); set => SetProperty(() => IsSelected, value); } }
应用启动流程总览
1. App.OnStartup ├── RegisterEvents() ← 三层全局异常捕获 ├── IconsHandler.Loading(...) ← 加载自定义图标集 └── InjectionWpf.Window<MainWindow, MainWindowViewModel>() └── WindowBase.SourceInitialized └── 加载 DarkTheme / LightTheme └── WindowBase 模板渲染 2. MainWindowViewModel 构造函数 ├── 构建 NavigationView 菜单树(Daq / Mq / 通信 / 工具) └── 构建底部菜单(关于) 3. 用户点击菜单项 → NavigationView 路由到对应的 View └── View 构造 → 设置 DataContext = new ViewModel() └── ViewModel 构造 → 初始化 BasicsData + Daq/Mq 实例 └── 加载 PropertyControl → 用户可编辑参数
🔌 第二十三章:插件热插拔架构
基于 .NET AssemblyLoadContext(isCollectible: true) 实现完整的运行时插件热加载/卸载,无需重启进程。Daq 同时支持 DAQ 采集插件 和 MQ 消息插件 两种类型。
加载流程
上传 ZIP 插件包 → 自动解压到插件目录 → 创建可回收 AssemblyLoadContext → 通过 MemoryStream 流式加载 DLL(无文件锁) → 扫描并实例化 IDaq / IMq 接口 → 注册到 IOC 容器 → 开始采集
卸载流程
停止采集 → 释放插件实例(IAsyncDisposable) → 移除 IOC 注册 → 卸载 AssemblyLoadContext → GC 回收 → 删除插件文件
技术亮点
| 特性 | 说明 |
|---|---|
| 可回收上下文 | AssemblyLoadContext(isCollectible: true),卸载后可被 GC 完整回收 |
| 流式加载 | MemoryStream + LoadFromStream 加载 DLL,避免文件锁定,卸载后立即可删除 |
| 类型一致性 | 共享接口程序集(IDaq、IMq)始终从默认上下文加载,确保 as 类型转换正确 |
| 并发安全 | ConcurrentDictionary 管理插件实例与上下文,支持多插件并发操作 |
| 双插件类型 | 同时支持 DAQ 和 MQ 两种插件接口 |
| PDB 符号 | 加载时自动附带 PDB 调试符号文件 |
插件契约
csharp// DAQ 采集插件 — 必须实现 IDaq 接口(Snet.Model/interface/IDaq.cs,17 子接口,含 IPacker) public interface IDaq : IOn, IOff, IRead, IWrite, ISubscribe, IStatus, IEvent, IArgs, IInstance, ILog, IWA, IObject, ILanguage, IClone, IPacker, IDisposable, IAsyncDisposable { } // MQ 消息插件 — 必须实现 IMq 接口(Snet.Model/interface/IMq.cs,13 子接口) public interface IMq : IOn, IOff, IProducer, IConsumer, IStatus, IEvent, IArgs, IInstance, ILog, ILanguage, IClone, IDisposable, IAsyncDisposable { }
PluginHandlerCore 核心 API
csharp// 获取插件 UI 配置 var plugins = PluginHandlerCore.GetPluginUIConfig<ObservableCollection<PluginListModel>>(configPath); // 初始化一个插件实例 PluginHandlerCore.PluginOperate.InitPlugin( pluginPath, // ZIP/DLL 路径 interfaceFullName); // "IDaq" 或 "IMq"
📊 第二十四章:ScottPlot 实时图表
基于 ScottPlot 的多曲线实时图表系统,支持主题跟随、皮肤切换、历史数据。
ChartHandler 封装扩展
// WpfPlot 扩展方法,位于 Snet.Iot.Daq.chart
csharpusing ScottPlot; using ScottPlot.WPF; // 创建散点连线(X + Y 数组) IPlottable line1 = wpfPlot.Create(xs: times, ys: values, "温度", Colors.Red); // 创建信号线(仅 Y 数组,自动生成 X 索引) IPlottable line2 = wpfPlot.Create(ys: samples, "压力", Colors.Blue); // 移除指定线条 wpfPlot.Remove(line1, out Exception? ex); // 移除所有线条 wpfPlot.RemoveAll(out ex); // 自动调整坐标轴并刷新 wpfPlot.Adjust(out ex);
ChartLine 自定义控件
xml<!-- ChartLine.xaml — 对 WpfPlot 的封装,添加图例、工具栏等 --> <local:ChartLine x:Name="TemperatureChart" />
csharp// ChartData — 包含图表配置和运行时数据 public class ChartData { public string Title { get; set; } public Color LineColor { get; set; } public List<double> XValues { get; set; } public List<double> YValues { get; set; } public double MaxPoints { get; set; } = 1000; // 最大数据点数(防内存溢出) }
XAML 使用
xml<local:ChartLine x:Name="MainChart" Margin="5" />
csharp// 动态添加数据(滚动窗口模式) MainChart.ScrollData(temperatureSeries, DateTime.Now, 25.6); MainChart.ScrollData(pressureSeries, DateTime.Now, 1.2);
🖥️ 第二十五章:系统监控仪表盘
⚠️ Daq/KMSim 应用代码,非 WpfMUI 库 API(命名空间
Snet.Windows.KMSim.utility,源码 F:/Snet/KMSim/Snet.Windows.KMSim/utility/SystemMonitoring.cs)。基于 LibreHardwareMonitor 的硬件信息采集。
SystemMonitoring 核心
csharpusing Snet.Windows.KMSim.utility; // 单例获取 + 生命周期 var monitor = SystemMonitoring.Instance(); monitor.Init(); // 启动硬件采集(内部初始化 LibreHardwareMonitor Computer) var info = monitor.GetInfo(); // 返回 HardwareData(含全部硬件信息) var info2 = monitor.GetInfo(true); // baseInfo=true 仅基础信息 monitor.End(); // 停止采集 monitor.Dispose(); // 释放(或 using var)
HardwareData 结构:
| 属性 | 说明 |
|---|---|
SystemName / SystemVer / SystemRunTime | 计算机名 / 系统版本 / 运行时长("X天X小时X分钟") |
CpuInfo / MemoryInfo / DiskInfo / GpuInfo / BiosInfo / NetworkInfo | 各硬件信息字符串 |
Info | List<HardwareDataType> 传感器明细(Key/Value) |
辅助方法: IsAdmin()(是否管理员)、IsOpen()(是否已启动采集)。
配合 LedGaugeControl 的仪表盘面板
xml<!-- 硬件状态面板(监控数据为字符串信息,用 Led 指示采集状态) --> <wpfui:Card> <StackPanel> <snet:TextBlockEx Text="系统状态" /> <StackPanel> <snet:LedGaugeControl Color="Green" IsOn="{Binding MonitorRunning}" /> <snet:TextBlockEx Text="{Binding CpuInfo}" /> <snet:TextBlockEx Text="{Binding MemoryInfo}" /> <snet:TextBlockEx Text="{Binding SystemRunTime}" /> </StackPanel> </StackPanel> </wpfui:Card>
❄️ 第二十六章:雪花粒子特效
⚠️ Daq 应用代码,非 WpfMUI 库 API(命名空间
Snet.Iot.Daq.effects,源码 F:/Snet/Daq/Snet.Iot.Daq/effects/SnowflakeEffect.cs)。WPF 纯渲染雪花飘落动画,主题色自动跟随(内部订阅 SkinHandler_OnSkinEvent)。
SnowflakeEffect 用法
csharp// 使用 Canvas 作为容器(雪花数量默认 188) var effect = new SnowflakeEffect(SnowCanvas); effect.Start(); // 开始动画(主题色跟随皮肤自动切换,无需手动 UpdateColor) effect.Stop(); // 停止动画
XAML 集成
xml<Grid> <!-- 主页内容 --> <Grid x:Name="HomeContent"> ... </Grid> <!-- 雪花覆盖层(IsHitTestVisible=False 不拦截鼠标事件) --> <Canvas x:Name="SnowCanvas" IsHitTestVisible="False" /> </Grid>
csharp// 在 Home 页面加载时启动,卸载时停止 var effect = new SnowflakeEffect(SnowCanvas); effect.Start(); // 页面关闭时:effect.Stop();
⚠️ 注意: 构造参数是
flakeCount(默认 188),没有count命名参数、UpdateColor或颜色构造参数——主题跟随通过内部SkinHandler_OnSkinEvent订阅自动完成。
🔒 第二十七章:单实例保护
⚠️ Daq 应用代码,非 WpfMUI 库 API(命名空间
Snet.Iot.Daq.Handler,源码 F:/Snet/Daq/Snet.Iot.Daq/handler/SingleInstanceHandler.cs)。基于命名 Mutex + NamedPipe 的单实例管理器,第二实例启动时自动激活已有窗口。
SingleInstanceHandler
csharp// 构造函数 — 创建全局 Mutex 判重 var single = new SingleInstanceHandler("MyApp", out bool isFirst); if (!isFirst) { // 第二实例:发送参数给第一实例,然后退出 single.SignalFirstInstance(new[] { "--file", "config.json" }); single.Dispose(); Application.Current.Shutdown(0); return; } // 第一实例:监听管道消息 single.SignalReceived += OnWakeup; single.RegisterMainWindow(mainWindow);
技术实现
| 组件 | 用途 |
|---|---|
Global\{AppName}_{UserName} Mutex | 进程唯一性判定,用户级隔离 |
NamedPipeServerStream (异步) | 接收第二实例的启动参数 |
NamedPipeClientStream | 向第一实例发送消息 |
BringToFront() | 恢复最小化、Show、Focus 三段激活 |
App.xaml.cs 完整集成
csharpprivate void OnStartup(object sender, StartupEventArgs e) { SingleInstance(e); // 判重 Init(); // IOC / 数据库 / 插件 RegisterEvents(); // 全局异常 IconsHandler.Loading("..."); // 图标 MainWindow window = InjectionWpf.Window<MainWindow, MainWindowModel>(true); window.Show(); singleInstance.RegisterMainWindow(window); // Show() 之后注册 HWND } private void Init() { // 注册 PropertyControl 单例到 IOC var control = new PropertyControl { ButtonVisibility = Visibility.Visible }; InjectionWpf.AddService(s => s.AddSingleton(control)); // 初始化 SQLite 数据库 GlobalConfigModel.sqliteOperate.CreateTable<AddressModel>(); // 加载已安装插件并启动 var plugins = PluginHandlerCore.GetPluginUIConfig<...>(configPath) ?? new(); foreach (var plugin in plugins) PluginHandlerCore.PluginOperate.InitPlugin(plugin.Path, interfaceName); // 加载配置数据 PluginHandler.GetAllPlugin(); AddressHandler.GetAllAddress(); ProjectHandler.GetAllProject(); }
🏠 第二十八章:Console 控制台日志系统
Daq 内置的彩色标签日志控制台,通过正则匹配日志标签自动标注颜色。
颜色标签映射
csharp// App.xaml.cs / App.EditModels(⚠️ 部分示例——Daq 实际约 79 条,含 On/Off/Read/Write/Send 等标签) private static List<EditModel> GetEditModels() => [ new() { Name = "[ Info ]", Color = "#4CAF50" }, // 绿色 new() { Name = "[ Error ]", Color = "#F44336" }, // 红色 new() { Name = "异常", Color = "#F44336" }, new() { Name = "Exception", Color = "#F44336" }, new() { Name = "[ Mq ]", Color = "#2196F3" }, // 蓝色 new() { Name = "[ Daq ]", Color = "#2196F3" }, new() { Name = "[ MqttService ]", Color = "#2196F3" }, new() { Name = "[ OpcUaService ]", Color = "#2196F3" }, new() { Name = "TRUE", Color = "#4CAF50" }, new() { Name = "FALSE", Color = "#F44336" }, new() { Name = ">", Color = "#FBC31D" }, // 黄色 new() { Name = "<", Color = "#FBC31D" }, ];
Console.xaml 控制台视图
xml<!-- 设备选择 + 日志输出 TextBox --> <snet:ComboBoxControl ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice}" /> <snet:TextBoxEx Text="{Binding ConsoleOutput}" AcceptsReturn="True" MoveFocusOnEnter="False" UpdateBindingOnEnter="False" IsReadOnly="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" />
事件绑定命令(EventCommand)
EventCommand 是 TriggerAction<DependencyObject>(继承 Microsoft.Xaml.Behaviors.Wpf),只能放在 Interaction.Triggers 的 EventTrigger 内,不能作为属性赋值:
xml<!-- ✅ 正确:用 Interaction.Triggers 包装(需 xmlns:b="http://schemas.microsoft.com/xaml/behaviors" + 安装 Microsoft.Xaml.Behaviors.Wpf 包) --> <snet:TextBoxEx Text="{Binding ConsoleOutput}" AcceptsReturn="True" MoveFocusOnEnter="False" UpdateBindingOnEnter="False"> <b:Interaction.Triggers> <b:EventTrigger EventName="TextChanged"> <snet:EventCommand Command="{Binding TextChangedCommand}" /> </b:EventTrigger> </b:Interaction.Triggers> </snet:TextBoxEx> <!-- ❌ 错误:TextChanged="{snet:EventCommand ...}" 属性写法 → XAML 解析失败 -->
EditBindingHandler 双向绑定
// F:/Snet/WpfMUI/Snet.Windows.Controls/handler/EditBindingHandler.cs // TextEditor(内嵌 AvalonEdit)的文本双向绑定附加属性: // h:EditBindingHandler.EditText="{Binding Code}"(BindsTwoWayByDefault) // 注意:该类与正则着色/FlowDocument 高亮无关;日志着色请用 TextEditor 的 Highlighting 机制。
⚙️ 第二十九章:地址字节级解析器
AddressSettings 与 Daq 的自动组包(DqaHandler/AddressAutoPackModel,见下文)实现可视化的字节/位/编码/数据格式配置,支持自定义协议解析。
核心概念
| 概念 | 说明 |
|---|---|
| 单地址 | 一个 AddressDetails 对应一个读取点位 |
| 自动组包 | 离散地址智能合并为批量读取,减少通信开销 |
| 字节解析 | BytesHandler.TransformAsync 根据 DataType/EncodingType/BitOffset 自动转换 |
| 数据格式 | String / Int / Float / Bool / Byte[] 及各自数组类型共 20 种 |
AddressModel 核心字段
csharp// F:/Snet/Daq/Snet.Iot.Daq.Core/data/AddressModelCore.cs // 继承 DaqPluginOperateModel.ReadModel(基类字段 Address/Type/Length/EncodingType)+ IAddressModel public class AddressModelCore : DaqPluginOperateModel.ReadModel, IAddressModel { // 基类 ReadModel:Address(string) / Type(DataType) / Length(ushort) / EncodingType(EncodingType) public int Index { get; set; } // 序号(主键自增) public string Guid { get; set; } // 唯一标识 public string AnotherName { get; set; } // 别名 public string Describe { get; set; } // 描述 public string Topic { get; set; } // 数据传输主题 public bool SimplifyValue { get; set; } // 数据传输精简值 public string ExpandParam { get; set; } // 扩展参数 public DateTime Time { get; set; } // 时间 public bool IsSelected { get; set; } // UI 选中 // + Update / Revoke / Convert 等命令 }
⚠️ 注意: 字段名是
Address/Type/Length/EncodingType(基类),没有SN/AddressName/DataType/AddressType/IsEnable/AddressMqParam属性。
自动组包(Daq 应用侧)
csharp// Daq 的自动组包能力在 Snet.Iot.Daq.Core: // - handler/DqaHandler.cs:341 — 批量订阅入口(autoPack 参数) // - data/AddressAutoPackModel.cs — 组包模型 // 底层组包算法本身由 Snet.Core 的 PackerHandler/PackerFactory 提供(见 DAQ-Skill §1.3)。 // ⚠️ 不存在 AutoPackHandler 类——旧文档虚构,勿引用。
AddressSettings 视图
⚠️ 示意示例: 绑定字段为
AddressModelCore的真实基类字段(Address/Type/Length/EncodingType+ 扩展AnotherName/Describe/IsSelected),非真实 Daq 视图结构——Daq 的AddressSettings.xaml是 QueryContent/QueryAddress/AddAddress 等命令布局。
xml<!-- AddressSettings 示意 — 绑定 AddressModelCore 真实字段 --> <wpfui:Card> <StackPanel> <snet:TextBlockEx Text="地址配置" /> <snet:DataGrid ItemsSource="{Binding Addresses}" AutoGenerateColumns="False"> <snet:DataGrid.ColumnDefinitions> <snet:ColumnDefinition Header="地址" PropertyName="Address" /> <snet:ColumnDefinition Header="类型" PropertyName="Type" /> <snet:ColumnDefinition Header="长度" PropertyName="Length" /> <snet:ColumnDefinition Header="编码" PropertyName="EncodingType" /> <snet:ColumnDefinition Header="选中" PropertyName="IsSelected" /> </snet:DataGrid.ColumnDefinitions> </snet:DataGrid> <snet:ButtonControl Content="添加地址" Command="{Binding AddAddressCommand}" /> </StackPanel> </wpfui:Card>
🔗 相关链接
| 链接 | 说明 |
|---|---|
| WpfMUI 仓库 | Snet.Windows.Core / Controls 源代码 |
| Daq 仓库 | 基于本框架的完整生产级桌面应用(插件热插拔、OPC UA Server、MQTT Broker、图表、系统监控) |
| NuGet 包 | Snet.Windows.Core / Controls |
| Snet 官网 | 文档和演示视频 |
| 演示视频 | 框架功能演示 |
📦 版本历史
| 版本 | 日期 | 变更 |
|---|---|---|
| 1.0.1.10 | 2026-11-13 | 同步 WpfMUI@b34f0bc(include_worktree=true,6项工作树文件见本轮外部状态);新增窗口独立 DialogHost/对话框共用队列、持久化与线程边界、PropertyGrid/编辑器/托盘行为;强制 Snet.Windows.Controls 优先,缺能力才用 Wpf.Ui,禁止原生交互控件回退;参考 Debug@429cb40 / Daq@0a7d5c9。 |
| 1.0.1.9 | 2026-10-29 | 同步WpfMUI@2131aa9(include_worktree=false)及Shunnet@89038d2(include_worktree=true,10个packer文件见本轮外部状态):安装基线26.301.1,MaterialDesignThemes5.4.0、Management/Drawing10.0.14。 |
| 1.0.1.8 | 2026-10-16 | 同步 WpfMUI @597b032、Shunnet @70421a7(include_worktree=false,源码干净):System.Management/System.Drawing.Common 10.0.13,区分当前源码ProjectReference依赖图与26.283.1安装基线。 |
| 1.0.1.7 | 2026-10-12 | 同步 WpfMUI @8027167、Shunnet @4664a25(include_worktree=false):安装基线 26.283.1,源码 1.0.0.0/ProjectReference;拖拽克隆/菜单/Canvas 坐标/旋转缩放锚点及释放边界,修正示例变量作用域和 Grid-only FAQ;托盘 TooltipText Unicode 即时更新、窗口 Foreground 动态主题资源。 |
| 1.0.1.6 | 2026-09-28 | 全量同步 WpfMUI @494ae6e(include_worktree=false):Snet.Windows.Core/Controls 与 Snet.Core 统一 26.256.1;补充 InjectionWpf 真同步解析及 HeaderedEntrySlider、DataGrid、WrapItemsOperator、FoldingManager、BitmapSourceTypeConverter、IconsHandler 的当前可靠性行为。 |
| 1.0.1.5 | 2026-09-10 | 补齐 DragControlsLayout / DragControlsLayoutItem 布局持久化模型与 NaturalStringComparer 公共 API;System.Management/System.Drawing.Common 依赖更新至 10.0.12 |
| 1.0.1.4 | 2026-09-08 | 对照源码升级(WpfMUI @9d2c664,88 文件;NuGet 26.236.1→26.250.2):安装命令与依赖树版本号更新(Snet.Windows.Core/Controls 26.250.2、Snet.Core 26.250.1);§5 ButtonControl CornerRadius 默认值 8→5;第七章 DragControls 性能优化新 API——DragControlsAnimate 新增 (Windows, LlayoutContainer, sources, …) 构造、Initialize、RegisterSource/CreateBySourceName/ContainsSourceName、附加属性 SourceName/SN/ExtensionData、EnableContextMenu/AttachCopyMenu/PinCopy/UnpinCopy/ExtractCopy/RemoveCopy/SetRotation/GetRotation/SettingsRequested/Detach,dragEvenTrigger 元组新增第 4 项 IsRotate(示例返回从 3 元组改 4 元组),MoveAndDragSizeInsert 增 Rotate=false 参数;DragControlsBase 增 Rotate=false 构造参数与 SurroundInnerColor/SurroundOuterColor/Angle/InitCentreThumb/InitRotateThumb/SetRotation/Detach;DragControlsHelper.Insert 增 Rotate、新增 Find;§6.2 UiMessageHandler.StartAsync 默认 intervalMs 100→200 且新增 CancellationToken 参数;其余 20+ 子控件公共 API 核对无变化(性能优化多为内部实现,ComboBox/TextBox 仅注释说明 Height 依赖属性);§9 托盘 TrayData 新增 Remove/AllocateId(internal 静态类,用户代码不可访问,无文档影响) |
| 1.0.1.3 | 2026-08-27 | 内置控件全覆盖:新增 §6.2「property/wpf 内置子控件全览(20+)」,逐一补充 ColorPicker、FilePicker、DirectoryPicker、RadioButtonList、SpinControl、FormattingTextBox、HeaderedEntrySlider、SliderEx、TextBoxEx、TextBlockEx、EditableTextBlock、CheckMark、EnumMenuItem、DockPanelSplitter、StackPanelEx、PopupBox、LinkBlock、PropertyGrid(独立版)、DataGrid(内置版,区别于 System DataGrid)、TreeListBox、ItemsBag、PropertyDialog、WizardDialog 的用法与关键属性,含独立使用前需合并 Generic.xaml 样式字典的说明、配套数据模型与 handler 工具类(EditHandler/ItemsControlHandler/UiMessageHandler/SettingsHandler);能力清单与 front-matter 同步更新 |
| 1.0.1.2 | 2026-08-24 | 对照源码升级(WpfMUI @bf4efed,NuGet 26.235.2→26.236.1):安装命令与依赖树版本号更新(Snet.Windows.Core/Controls 26.236.1、Snet.Core 26.236.1) |
| 1.0.1.1 | 2026-08-24 | 对照源码升级(WpfMUI @92affc7,NuGet 26.226.1→26.235.2):安装命令与依赖树版本号更新(Snet.Windows.Core/Controls 26.235.2、Snet.Core 26.235.2) |
| 1.0.1.0 | 2026-08-14 | 对照源码升级(WpfMUI @390d732,NuGet 26.222.1→26.226.1):安装命令与依赖树版本号更新(Snet.Core 系 26.226.1、System.Management/System.Drawing.Common 10.0.10→10.0.11);§29 AddressSettings 示例改为绑定 AddressModelCore 真实字段(Address/Type/Length/EncodingType/IsSelected)并标注示意性质 |
| 1.0.0.9 | 2026-08-11 | 对照 WpfMUI 源码升级:NuGet 版本 26.214.1→26.222.1;依赖树移除 AvalonEdit(v26.222.1 起源码内嵌);第五章新增"编辑控件 TextEditor/TextEditorControl"(Snet.Windows.Controls.edit,替代旧 AvalonEdit xmlns);第六章修正:注解 using 改 Snet.Windows.Controls.property.core.DataAnnotations(非 property.wpf)、ItemsSourceProperty 实参为字符串属性名、Spinnable 4 参构造(无 3 参)、InputFilePath 单参=默认扩展名;第四章补 SetLanguageAsync 异步优先 + LanguageHandler 双命名空间歧义警示(事件真身在 Snet.Core.handler);第七章补 MessageEvenTrigger 与 DragControlsExcessiveAnimate;code-review 修正:第十章 Spinnable 4 参、第十一章图标 key 改真实值、第十五/二十二章模板 VM 标注为示意架构(类不存在)、第二十一章 OPC UA 模型改真实路径/成员(Snet.Iot.Debug.model)、第二十三/二十九章 IDaq 17 接口/AddressModelCore 真实字段、第二十五/二十六/二十七章 SystemMonitoring/SnowflakeEffect/SingleInstanceHandler 按真实 API 重写+来源标注、第二十八章 EventCommand 改 Interaction.Triggers 用法/EditBindingHandler 说明重写、第六章 Width/Height 注解签名/using System.Windows.Media、依赖树补 System.Management/System.Drawing.Common、删除虚构 AutoPackHandler 指向 DqaHandler |
| 1.0.0.8 | 2026-08-02 | 全面核对源码修正:XAML xmlns https://shunnet.top→https://snet.cn(5 处);删除虚构 GetSkinAsync(仅同步 GetSkin);托盘章节重写(NotifyIcon 是 XAML 元素 + Register/Unregister/点击事件,TrayManager 为 internal 不可访问);Win32Handler.Select 参数 isFolder→selectFolder(且不支持多选);dragEvenTrigger→DragEvenTrigger(委托带参);PropertyGrid using 去 .PropertyGrid 后缀;事件参数 e.SkinType→e.Skin;SetProperty(expr,val,null) 三参歧义→两参;CreationControl 第 4 参 multilingual;GifHandler 命名空间 Snet.Iot.Debug.handler;SystemMonitoring 路径修正;NuGet 版本 1.0.0.1→26.214.1 |
| 1.0.0.7 | 2026-07-14 | 初始版本:WindowBase、6 大控件、MVVM、主题、多语言、拖拽、托盘、PropertyGrid、NavigationView、模板视图架构、全局异常处理、异步日志、文件对话框、GIF/SVG 转换、OPC UA 节点浏览、完整架构实战、Daq 插件热插拔、ScottPlot 图表、系统监控、雪花特效、单实例保护、Console 控制台、地址字节级解析器(共 29 章) |


