3.3 KiB
3.3 KiB
Sharp.Wpf
WPF 常用基础能力工具包,开箱即用:
- 全局异常处理:统一捕获 UI/后台异常,弹窗与日志钩子
- MVVM 基础:ViewModelBase、RelayCommand、AsyncCommand
- Dispatcher 封装:IDispatcher/DispatcherService
- 对话与文件对话:IDialogService、IFileDialogService
- 常用转换器:Bool/NullOrEmpty 可见性、布尔取反、枚举描述
- 附加行为:EventToCommand(事件转 ICommand)
- 窗口工具:WindowPlacement(位置/大小/状态持久化)
安装/引用
- 作为仓库子项目引用:
<ItemGroup>
<ProjectReference Include="..\Wpf\Wpf.csproj" />
</ItemGroup>
- 或通过 NuGet(计划发布):
<PackageReference Include="Sharp.Wpf" Version="x.y.z" />
快速上手
- 在 App 启动注册全局异常处理
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 = "应用程序错误"
});
}
}
- 在 XAML 启用窗口位置记忆、事件到命令、可见性转换器
<Window x:Class="Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:Sharp.Wpf.Behaviors;assembly=Sharp.Wpf"
xmlns:w="clr-namespace:Sharp.Wpf.Windowing;assembly=Sharp.Wpf"
xmlns:conv="clr-namespace:Sharp.Wpf.Converters;assembly=Sharp.Wpf"
w:WindowPlacement.RememberPlacement="True"
w:WindowPlacement.PlacementId="MainWindow">
<Window.Resources>
<conv:BoolToVisibilityConverter x:Key="Bool2Vis" />
</Window.Resources>
<StackPanel>
<Button Content="点击弹窗"
b:EventToCommand.EventName="Click"
b:EventToCommand.Command="{Binding ShowDialogCommand}" />
<TextBlock Text="处理中..."
Visibility="{Binding IsBusy, Converter={StaticResource Bool2Vis}}"/>
</StackPanel>
</Window>
- ViewModel 使用命令与对话服务
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; }
});
}
}
- 文件/文件夹对话
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"。