Sharp.Wpf
=========
WPF 常用基础能力工具包,开箱即用:
- 全局异常处理:统一捕获 UI/后台异常,弹窗与日志钩子
- MVVM 基础:ViewModelBase、RelayCommand、AsyncCommand
- Dispatcher 封装:IDispatcher/DispatcherService
- 对话与文件对话:IDialogService、IFileDialogService
- 常用转换器:Bool/NullOrEmpty 可见性、布尔取反、枚举描述
- 附加行为:EventToCommand(事件转 ICommand)
- 窗口工具:WindowPlacement(位置/大小/状态持久化)
安装/引用
---------
- 作为仓库子项目引用:
```xml
```
- 或通过 NuGet(计划发布):``
快速上手
--------
1) 在 App 启动注册全局异常处理
```csharp
using System.Windows;
using Sharp.Wpf.Exceptions;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new UiExceptionHandler().Register(new ExceptionHandlingOptions
{
ShowDialog = true,
DialogTitle = "应用程序错误"
});
}
}
```
2) 在 XAML 启用窗口位置记忆、事件到命令、可见性转换器
```xml
```
3) ViewModel 使用命令与对话服务
```csharp
using System;
using System.Threading.Tasks;
using Sharp.Wpf.Commands;
using Sharp.Wpf.Mvvm;
using Sharp.Wpf.Services;
public sealed class MainViewModel : ViewModelBase
{
private readonly IDialogService _dialog = new DialogService();
public IAsyncCommand ShowDialogCommand { get; }
public MainViewModel()
{
ShowDialogCommand = new AsyncCommand(async () =>
{
try { IsBusy = true; await Task.Delay(300); await _dialog.ShowInfoAsync("Hello!"); }
finally { IsBusy = false; }
});
}
}
```
4) 文件/文件夹对话
```csharp
var file = await new FileDialogService().OpenFileAsync("All Files|*.*");
var folder = await new FileDialogService().SelectFolderAsync();
```
注意
----
- 需要 `UseWPF` 与 `net8.0-windows` 目标框架。
- 本库同时启用 `UseWindowsForms` 以使用系统文件夹选择对话框。
- 若要禁用全局异常弹窗,可在 `ExceptionHandlingOptions` 中设置 `ShowDialog = false` 并仅使用 `Log` 钩子记录。
- `EventToCommand` 通过反射订阅事件,适用于大多数 Routed 事件;如需传递事件参数,可设置 `PassEventArgsToCommand="True"`。