# 01 - 最小 WPF 应用 这是一个最简单的 Sharp WPF 应用示例,演示了框架的基础用法。 ## 🎯 学习目标 - 了解 Sharp 框架的基本结构 - 掌握 MVVM 模式(ViewModelBase) - 使用 Commands(RelayCommand, AsyncCommand) - 使用对话框服务(IDialogService) - 理解 Quick Start 配置方式 ## 📦 使用的模块 - **Sharp.Common** - Result, 基础工具 - **Sharp.Config** - 配置管理 - **Sharp.Wpf** - MVVM 基础设施 ## 🏗️ 项目结构 ``` 01-MinimalWpfApp/ ├── App.xaml # 应用程序入口 ├── App.xaml.cs # Quick Start 配置 ├── MainWindow.xaml # 主窗口界面 ├── MainWindow.xaml.cs # 主窗口代码隐藏 ├── ViewModels/ │ └── MainViewModel.cs # 主窗口 ViewModel ├── appsettings.json # 配置文件 └── README.md # 本文件 ``` ## 🚀 快速运行 ```bash cd examples/01-MinimalWpfApp dotnet run ``` ## 📝 核心代码讲解 ### 1. App.xaml.cs - 应用启动 ```csharp protected override void OnStartup(StartupEventArgs e) { var services = new ServiceCollection(); // 一行添加基础服务(配置、日志、缓存) services.AddSharpEssentials(); // 一行添加 WPF 服务(对话框、调度器、导航、主题) services.AddSharpWpf(); // 注册 ViewModel 和 Window services.AddViewModel(); services.AddTransient(); // 构建服务提供者 _serviceProvider = services.BuildServiceProvider(); // 显示主窗口 var mainWindow = _serviceProvider.GetRequiredService(); mainWindow.Show(); } ``` **关键点**: - `AddSharpEssentials()` - 自动配置 Config + Log + Cache - `AddSharpWpf()` - 自动注册 WPF 服务 - 无需手动配置,使用约定优于配置 ### 2. MainViewModel.cs - ViewModel 示例 ```csharp public class MainViewModel : ViewModelBase { private readonly IDialogService _dialogService; private string _message = "Hello, Sharp!"; private int _counter = 0; public string Message { get => _message; set => SetProperty(ref _message, value); } public int Counter { get => _counter; set => SetProperty(ref _counter, value); } // 同步命令 public ICommand IncrementCommand { get; } // 异步命令 public ICommand ShowDialogCommand { get; } public MainViewModel(IDialogService dialogService) { _dialogService = dialogService; // RelayCommand - 同步操作 IncrementCommand = new RelayCommand(() => { Counter++; Message = $"你点击了 {Counter} 次"; }); // AsyncCommand - 异步操作 ShowDialogCommand = new AsyncCommand(async (ct) => { IsBusy = true; // 显示加载状态 // 模拟耗时操作 await Task.Delay(1000, ct); _dialogService.ShowMessage($"当前计数: {Counter}", "提示"); IsBusy = false; }); } } ``` **关键点**: - 继承 `ViewModelBase` 获得 INotifyPropertyChanged - 使用 `SetProperty()` 自动触发属性变化通知 - `IsBusy` 属性用于显示加载状态 - `RelayCommand` 用于同步操作 - `AsyncCommand` 用于异步操作(支持取消) ### 3. MainWindow.xaml - 界面绑定 ```xml