Galosys.Foundation.Wpf
26.10.29.1
dotnet add package Galosys.Foundation.Wpf --version 26.10.29.1
NuGet\Install-Package Galosys.Foundation.Wpf -Version 26.10.29.1
<PackageReference Include="Galosys.Foundation.Wpf" Version="26.10.29.1" />
<PackageVersion Include="Galosys.Foundation.Wpf" Version="26.10.29.1" />
<PackageReference Include="Galosys.Foundation.Wpf" />
paket add Galosys.Foundation.Wpf --version 26.10.29.1
#r "nuget: Galosys.Foundation.Wpf, 26.10.29.1"
#:package Galosys.Foundation.Wpf@26.10.29.1
#addin nuget:?package=Galosys.Foundation.Wpf&version=26.10.29.1
#tool nuget:?package=Galosys.Foundation.Wpf&version=26.10.29.1
Galosys.Foundation.Wpf
WPF 桌面应用 MVVM 基础设施模块,提供 DI 集成、页面导航、菜单管理、认证授权、权限检查和自动更新。
成熟度: 🟢 生产就绪 — 核心功能已验证,API 稳定 目标框架:
net10.0-windows
安装
<PackageReference Include="Galosys.Foundation.Wpf" />
最小化配置
// App.xaml.cs
public partial class App : Application
{
private IHost _host;
public App()
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices((ctx, services) =>
{
services.AddCore(ctx.Configuration) // 核心基础设施
.AddWpf() // MVVM + 导航 + 菜单 + 权限 + 自动更新
.AddHttpClient(); // HttpClient 工厂
services.Configure<MenuOptions>(ctx.Configuration.GetSection("Menu"));
})
.Build();
Ioc.Default.ConfigureServices(_host.Services);
}
protected override void OnStartup(StartupEventArgs e)
{
var login = Ioc.Default.GetRequiredService<LoginView>();
login.Show();
MainWindow = login;
}
protected override async void OnExit(ExitEventArgs e)
{
if (_host is IAsyncDisposable asyncDisposable)
await asyncDisposable.DisposeAsync();
else
_host.Dispose();
base.OnExit(e);
}
}
appsettings.json
{
"Auth": {
"Mode": "Local",
"OAuth2": {
"TokenEndpoint": "",
"ClientId": "",
"ClientSecret": "",
"Scope": "openid profile"
}
},
"Menu": {
"Source": "Local",
"ApiEndpoint": "/api/v1/menus",
"Items": [
{ "Path": "首页", "Route": "HomePage", "Icon": "Home", "Order": 0 },
{ "Path": "设置", "Route": "SettingsView", "Icon": "Settings", "Order": 99 }
]
}
}
三模块链式注册
Wpf 模块与 Wpf.Controls、Wpf.Pro 支持链式注册:
services.AddCore(ctx.Configuration)
.AddWpf() // MVVM + IPageResolver + INavigationService + IMenuProvider + IPermissionService + IAutoUpdateService
.AddWpfControls() // 扩展控件(Switch, Card, Modal, Drawer, Toast...)
.AddWpfPro() // 高级组件(ProDataGrid, ProForm, ProLayout)
.AddHttpClient();
AddWpf()内部自动调用AddMvvm(),无需手动调用。
功能一览
核心注册
| 功能 | 说明 |
|---|---|
AddWpf() |
主入口:调用 AddMvvm() + 注册 IPageResolver、INavigationService、IMenuProvider、IPermissionService、IAutoUpdateService、IMessenger、ISessionService |
AddMvvm() |
扫描程序集,注册 ViewModel (Transient)、Window (Transient)、Page (Transient),自动绑定 DataContext |
ExceptionHandlerBinder |
全局异常捕获(AppDomain / Dispatcher / TaskScheduler),注入 ILogger<T> + IErrorHandler,自动在 AddMvvm() 中注册 |
IExceptionHandlerBinder |
统一异常处理接口,支持自定义错误策略 |
导航
| 功能 | 说明 |
|---|---|
IPageResolver |
页面解析器:ViewModel 绑定、视图解析(ResolveViewModel、ResolveViewType、GetView) |
INavigationService |
导航服务接口(默认 SimpleNavigationService,可由 Galosys.Foundation.AvalonDock 覆盖为 DockingNavigationService)。NavigateToAsync 支持 NavigationContext 类型化参数,旧签名标记 [Obsolete] |
INavigationAware |
导航生命周期接口(OnNavigatedTo(NavigationContext) / OnNavigatedFrom),旧 OnNavigatedTo(object) 标记 [Obsolete] |
NavigationContext |
类型化导航参数(Route + IReadOnlyDictionary<string, object>,Get<T>(key) 类型安全提取) |
IConfirmNavigation |
导航拦截接口(CanNavigateFrom() / CanNavigateFromAsync()),支持脏数据确认 |
[Shell] |
标记主窗口类 |
AvalonPageNavigator |
AvalonDock 标签页导航器(已迁移至 Galosys.Foundation.AvalonDock) |
菜单管理
| 功能 | 说明 |
|---|---|
IMenuProvider |
菜单提供者接口(GetMenusAsync → IReadOnlyList<MenuItemDto>) |
LocalMenuProvider |
从 appsettings.json Menu:Items 配置节读取菜单 |
ApiMenuProvider |
HTTP + JWT 调中台菜单接口 |
MenuItemDto |
统一菜单模型(Path, Route, Icon, Order, Permission, Children) |
MenuOptions |
配置映射(Source, ApiEndpoint, Items) |
认证
| 功能 | 说明 |
|---|---|
IAuthenticationService |
认证服务接口(登录 / 登出 / 当前用户) |
OAuth2AuthService |
OAuth2 密码模式认证,支持 JWT 解析与 Token 自动刷新 |
LocalAuthService |
本地 SQLite + PBKDF2 认证(自动建库、默认 admin 账户) |
DpapiTokenStorage |
DPAPI 加密 Token 安全存储 |
LoginViewModelBase |
登录 ViewModel 基类 |
权限
| 功能 | 说明 |
|---|---|
IPermissionService |
RBAC 权限检查接口 |
DefaultPermissionService |
基于内存缓存的权限服务,支持自定义 PermissionLoader 委托 |
自动更新
| 功能 | 说明 |
|---|---|
IAutoUpdateService |
自动更新接口(版本检查 + 后台下载 + 提示更新) |
AutoUpdateService |
HTTP 版本检查 + temp/ 下载 + ConfirmUpdateCallback + 跳过版本 |
AutoUpdateOptions |
配置(UpdateUrl, CurrentVersion, CheckIntervalMinutes, DownloadFolder) |
辅助工具
| 功能 | 说明 |
|---|---|
HttpClientExtensions |
GetAsync<T>(url, param?) / PostAsync<T>(url, body) 扩展方法 |
ControlTreeHelper |
可视化树查找辅助(GetParent / GetChild / ChildrenOfType / ExpandTreeView) |
ControlFinder |
按名称/类型递归查找控件 |
EnumBindingSourceExtension |
XAML 中绑定枚举值 |
EnumDescriptionTypeConverter |
枚举 Description 特性转字符串 |
SimpleSetting<T> |
XML 文件设置持久化 |
TextBoxHelper / ButtonHelper / TextBlockHelper / ProgressBarHelper / BorderHelper |
辅助附加属性(已从 Controls 层迁入 Foundation 层) |
IPageResolver — 页面解析器
IPageResolver 统一管理 ViewModel 绑定和视图解析。Page 类无需属性装饰,路由匹配按类名自动解析。
public interface IPageResolver
{
object? ResolveViewModel(Type viewType); // 视图 → ViewModel 实例
Type? ResolveViewType(string route); // 路由 → 视图类型(按类名匹配)
object GetView(Type pageType); // 从 DI 获取视图(DataContext 已绑定)
}
使用示例
var resolver = Ioc.Default.GetRequiredService<IPageResolver>();
// 根据路由解析视图(按 Page 类名匹配)
var viewType = resolver.ResolveViewType("HomePage");
var view = resolver.GetView(viewType); // DataContext 已自动绑定 ViewModel
ViewModel 绑定约定
自动按命名空间约定匹配 ViewModel:
| 视图 | ViewModel | 匹配规则 |
|---|---|---|
MyApp.Views.UserListPage |
MyApp.ViewModels.UserListPageViewModel |
.Views. → .ViewModels. + ViewModel 后缀 |
MyApp.Views.UserListPage |
MyApp.ViewModels.UserListPageVm |
同上 + Vm 后缀 |
UserPage |
UserPageViewModel |
兜底:名称包含匹配 |
IMenuProvider — 菜单提供者
菜单配置驱动,支持 Local(配置文件)和 Api(中台 HTTP)双模式。Page 类无需任何菜单元数据属性。
Local 模式
// appsettings.json
{
"Menu": {
"Source": "Local",
"Items": [
{ "Path": "首页", "Route": "HomePage", "Icon": "Home", "Order": 0 },
{ "Path": "系统管理", "Icon": "Settings", "Order": 10, "Children": [
{ "Path": "用户管理", "Route": "UserListPage", "Icon": "Users", "Order": 1 },
{ "Path": "角色管理", "Route": "RoleListPage", "Icon": "Shield", "Order": 2 }
]}
]
}
}
// 绑定配置
services.Configure<MenuOptions>(ctx.Configuration.GetSection("Menu"));
// 使用
var menuProvider = Ioc.Default.GetRequiredService<IMenuProvider>();
var menus = await menuProvider.GetMenusAsync();
// menus[0].Path = "首页", menus[0].Route = "HomePage"
Api 模式
{
"Menu": {
"Source": "Api",
"ApiEndpoint": "/api/v1/menus"
}
}
Api 模式下,ApiMenuProvider 自动附加 JWT Bearer Token 请求中台菜单接口。
MenuItemDto 模型
| 属性 | 类型 | 说明 |
|---|---|---|
| Path | string | 菜单显示名称 |
| Route | string? | 路由名称(对应 Page 类名) |
| Icon | string? | 图标名称(Lucide 风格) |
| Order | int | 排序序号 |
| Permission | string? | 权限标识 |
| Children | List<MenuItemDto>? | 子菜单 |
INavigationService — 导航服务
SimpleNavigationService — 单页导航
适用于工具类单页应用,基于 Frame.Navigate:
var navigation = Ioc.Default.GetRequiredService<INavigationService>();
// 在 Shell 窗口中设置 Frame
if (navigation is SimpleNavigationService simpleNav)
simpleNav.Frame = MainFrame;
// 导航到指定路由
await navigation.NavigateToAsync("HomePage");
await navigation.NavigateToAsync("UserDetailPage", new NavigationContext { ["id"] = 42 }); // 类型化参数
// 回退
if (navigation.CanGoBack)
await navigation.GoBackAsync();
DockingNavigationService — 多标签页导航
适用于企业级多文档应用,基于 AvalonDock。需额外引用 Galosys.Foundation.AvalonDock 模块:
// 注册链中添加 AddAvalonDock()
services.AddCore(ctx.Configuration)
.AddWpf()
.AddAvalonDock() // 覆盖默认 SimpleNavigationService
.AddWpfControls();
// 使用方式不变
var navigation = Ioc.Default.GetRequiredService<INavigationService>();
if (navigation is DockingNavigationService dockingNav)
{
dockingNav.DockingManager = dockingManager;
dockingNav.DocumentPane = documentPane;
}
await navigation.NavigateToAsync("OrderListPage");
INavigationAware — 导航生命周期
public partial class UserDetailPage : Page, INavigationAware
{
public void OnNavigatedTo(NavigationContext context)
{
var userId = context.Get<int>("id");
}
public void OnNavigatedTo(object parameter) { } // 旧签名,标记 [Obsolete]
public void OnNavigatedFrom() { }
}
IConfirmNavigation — 导航拦截
实现 IConfirmNavigation 接口可在离开页面前拦截导航,常用于脏数据确认:
public partial class EditPage : Page, IConfirmNavigation
{
private bool _isDirty;
public bool CanNavigateFrom()
{
if (_isDirty)
{
var result = MessageBox.Show("有未保存的修改,确定离开?", "确认", MessageBoxButton.YesNo);
return result == MessageBoxResult.Yes;
}
return true;
}
public async Task<bool> CanNavigateFromAsync()
{
// 或使用异步确认对话框
return await ConfirmAsync("有未保存的修改,确定离开?");
}
}
认证
OAuth2 远程认证
services.Configure<OAuth2Options>(configuration.GetSection("Auth:OAuth2"));
services.AddSingleton<ITokenStorage>(new DpapiTokenStorage("MyApp"));
services.AddSingleton<IAuthenticationService, OAuth2AuthService>();
本地 SQLite 认证
services.AddSingleton<IAuthenticationService>(new LocalAuthService("MyApp"));
LoginViewModelBase — 登录基类
// 推荐:注入 IAuthenticationService
public class LoginVm : LoginViewModelBase
{
public LoginVm(IAuthenticationService authService)
: base(authService, () => Ioc.Default.GetRequiredService<ShellWindow>()) { }
}
自动更新
// 配置
services.Configure<AutoUpdateOptions>(configuration.GetSection("AutoUpdate"));
// 使用
var updateService = Ioc.Default.GetRequiredService<IAutoUpdateService>();
// 检查更新
var update = await updateService.CheckUpdateAsync();
if (update != null)
{
// 设置确认回调(由应用层决定 UI)
updateService.ConfirmUpdateCallback = info =>
{
// 显示更新提示 UI,返回 true/false
return MessageBox.Show($"发现新版本 {info.Version},是否更新?") == MessageBoxResult.Yes;
};
await updateService.PromptUpdateAsync(update);
}
IErrorHandler — 全局错误处理
系统提供 IErrorHandler 接口和 ErrorPolicy 枚举(Notify/Retry/Fatal)实现统一错误策略分发。
public interface IErrorHandler
{
Task<ErrorPolicy> HandleAsync(Exception exception, string? context = null);
}
异常处理
ExceptionHandlerBinder 已在构造函数中新增可选参数 IExceptionPipeline? pipeline = null,用于在 DI 配置时直接注入 Core 的统一分发管道:
// 静态兼容入口(无 pipeline,保留既有 LogError + IErrorHandler.HandleAsync 行为)
ExceptionHandlerBinder.Bind();
// 通过 AddMvvm() 由 DI 注入 pipeline + logger + IErrorHandler
services.AddMvvm(); // 自动注册 ExceptionHandlerBinder 并解析 pipeline
// 或显式构造
var binder = new ExceptionHandlerBinder(
logger: loggerFactory.CreateLogger<ExceptionHandlerBinder>(),
errorHandler: errorHandler,
pipeline: serviceProvider.GetRequiredService<IExceptionPipeline>());
三个全局事件(AppDomain.UnhandledException / Dispatcher.DispatcherUnhandledException / TaskScheduler.UnobservedTaskException)均委托 IExceptionPipeline.Process(ex, traceId, source),由统一的优先级分发器接管;未注入 pipeline 时沿用既有 LogError + IErrorHandler.HandleAsync 兼容路径。IErrorHandler / ErrorPolicy 类型签名保持不变。
ErrorBoundary — 渲染异常兜底
ErrorBoundary 控件(位于 Galosys.Foundation.Wpf.Controls)包裹子内容,捕获渲染异常后显示错误信息 + 重试按钮。
<galosys:ErrorBoundary>
<local:MyComplexControl />
</galosys:ErrorBoundary>
IMessenger — 事件总线
AddWpf() 自动将 IMessenger 注册为 WeakReferenceMessenger Singleton,ViewModel 之间通过消息解耦通信:
public class OrderViewModel
{
private readonly IMessenger _messenger;
public OrderViewModel(IMessenger messenger)
{
_messenger = messenger;
}
public void Submit()
{
_messenger.Send(new OrderSubmittedMessage(orderId));
}
}
public class LogViewModel : IRecipient<OrderSubmittedMessage>
{
public LogViewModel(IMessenger messenger)
{
messenger.RegisterAll(this);
}
public void Receive(OrderSubmittedMessage message) { }
}
ISessionService — 应用状态管理
跨 ViewModel 共享状态的键值存储,线程安全,变更时通过 IMessenger 通知:
public class ProfileViewModel
{
private readonly ISessionService _session;
public ProfileViewModel(ISessionService session)
{
_session = session;
}
public void Login(string user) => _session.Set("CurrentUser", user);
public string? GetUser() => _session.Get<string>("CurrentUser");
}
ViewModelLocator — AutoWire 附加属性
提供 ViewModelLocator.AutoWireViewModel 附加属性,在控件 Loaded 时自动从 DI 解析 ViewModel 并设置 DataContext:
<Page xmlns:galosys="https://galosys.com/wpf"
galosys:ViewModelLocator.AutoWireViewModel="True"
d:DataContext="{d:DesignInstance Type=viewmodels:DesignUserViewModel, IsDesignTimeCreatable=True}">
运行时 ViewModelLocator 按命名空间约定(.Views. → .ViewModels. + ViewModel/Vm 后缀)自动解析 ViewModel。
AutoUpdateOptions 配置
{
"AutoUpdate": {
"UpdateUrl": "https://update.example.com/check",
"CurrentVersion": "1.0.0",
"CheckIntervalMinutes": 60,
"DownloadFolder": "temp"
}
}
Breaking Changes(相对旧版本)
| 旧 API | 新 API | 说明 |
|---|---|---|
[GalosysPage("菜单路径")] |
appsettings.json Menu:Items | 菜单元数据从属性迁移到 JSON 配置 |
[Page("模板路径")] |
已删除 | Page 类无需任何属性装饰 |
IPageResolver.GetMenuCandidates() |
IMenuProvider.GetMenusAsync() |
菜单发现迁移到独立的 IMenuProvider |
Ioc.Default.GetMenuCandidates() |
IMenuProvider.GetMenusAsync() |
同上 |
services.AddMvvm() |
services.AddWpf() |
AddWpf() 内部调用 AddMvvm() |
ViewModelLocator / ViewModelLocationProvider |
IPageResolver |
统一页面解析 |
Modal (static API) |
Modal (ContentControl + ShowAsync) |
重构为 ContentControl |
LoginWindowVmBase<T> |
LoginViewModelBase |
非泛型 |
NAudio / Audio 目录 |
已删除 | 音频功能移除 |
依赖
- Galosys.Foundation.Core
- CommunityToolkit.Mvvm
- Microsoft.Extensions.Http
- Microsoft.Data.Sqlite(本地认证)
AvalonDock 相关依赖已拆分至独立模块
Galosys.Foundation.AvalonDock。BCrypt 已替换为 .NET 内置 PBKDF2。
Wpf.Foundation — 轻量级工具开发套件
面向简单工具软件(配置面板、文件处理器、数据转换器等单窗口工具)的轻量方案。一行启动、原生风格、零样板 MVVM。
Quick Start
// App.xaml.cs — 最小启动
services.AddCore(configuration).AddWpf().UseFoundation();
// MainViewModel.cs — 零样板代码
[ObservableObject]
public partial class MainViewModel
{
[ObservableProperty] private string _inputText;
[ObservableProperty] private string _outputText;
[RelayCommand]
private async Task ProcessAsync()
{
OutputText = await SomeService.ProcessAsync(InputText);
ToastService.Success("处理完成");
}
}
<StackPanel>
<TextBox Text="{Binding InputText}" AcceptsReturn="True"/>
<Button Content="处理" Command="{Binding ProcessCommand}"/>
<TextBox Text="{Binding OutputText}" IsReadOnly="True"/>
</StackPanel>
功能
| 功能 | 说明 |
|---|---|
UseFoundation() |
一行注册全部 Foundation 服务 + 注入隐式样式 |
IFileDialogService |
文件打开/保存/文件夹选择对话框 |
IProgressDialogService |
带进度条的模态对话框 |
IToastService |
窗口内 Toast 通知(Success/Error/Info/Warning) |
| 隐式样式 | Foundation 密集直角隐式样式(CornerRadius=0, 12px, 灰度色系) |
| Lucide 图标 | 1700+ Lucide SVG 图标 Geometry 资源,按需合并 |
Lucide 图标
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Galosys.Foundation.Wpf;component/System/Windows/Foundation/Styles/FoundationTheme.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Galosys.Foundation.Wpf;component/System/Windows/Foundation/Styles/Lucide.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
<Path Data="{DynamicResource Search}" Width="14" Height="14"
Fill="{DynamicResource TextBrush}" Stretch="Uniform"/>
1700+ 图标,命名规则:kebab-case → PascalCase(
file-plus→FilePlus)
与 Controls/Pro 的关系
Foundation 和 Controls/Pro 面向不同场景,可独立使用也可共存:
| Foundation | Controls + Pro | |
|---|---|---|
| 定位 | 简单工具开发 | 管理系统开发 |
| 控件 | 原生 WPF Dense 密度隐式样式 | 扩展控件(Switch, Card, Modal, Drawer...) |
| 接入 | 一行 UseFoundation() |
多步骤注册 + ResourceDictionary 合并 |
| 主题 | Foundation 风格(固定 Light 主题) | 完整明暗主题切换 |
| 体积 | ~50KB | ~500KB+ |
// 共存时 Controls 显式样式自动覆盖 Foundation 隐式样式
services.AddCore(configuration)
.AddWpf()
.UseFoundation() // Foundation 基础
.AddWpfControls() // Controls 显式样式优先
.AddWpfPro();
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows7.0 is compatible. |
-
net10.0-windows7.0
- communitytoolkit.mvvm (>= 8.2.1)
- Galosys.Foundation.Core (>= 26.10.29.1)
- microsoft.data.sqlite (>= 8.0.8)
- microsoft.extensions.http (>= 10.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Galosys.Foundation.Wpf:
| Package | Downloads |
|---|---|
|
Galosys.Foundation.AvalonDock
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.Wpf.Controls
Galosys.Foundation快速开发库 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 26.10.29.1 | 137 | 10/29/2026 |
| 26.10.20.1 | 118 | 10/20/2026 |
| 26.10.16.2 | 121 | 10/16/2026 |
| 26.10.16.1 | 128 | 10/16/2026 |
| 26.10.9.1 | 118 | 10/9/2026 |
| 26.10.8.1 | 124 | 10/8/2026 |
| 26.9.23.1 | 137 | 9/23/2026 |
| 26.9.16.1 | 129 | 9/16/2026 |
| 26.9.15.1 | 124 | 9/15/2026 |
| 26.9.14.1 | 131 | 9/15/2026 |
| 26.8.29.1 | 141 | 8/31/2026 |
| 26.8.26.1 | 138 | 8/26/2026 |
| 26.8.23.1 | 159 | 8/23/2026 |
| 26.8.21.1 | 149 | 8/21/2026 |
| 26.8.20.1 | 164 | 8/20/2026 |
| 26.8.18.1 | 148 | 8/18/2026 |
| 26.8.17.1 | 146 | 8/17/2026 |
| 26.8.13.2 | 148 | 8/13/2026 |
| 26.8.13.1 | 143 | 8/13/2026 |
| 26.8.12.2 | 126 | 8/12/2026 |