# 06 - 主题系统示例 演示如何使用 Sharp.Wpf 的主题系统实现浅色/深色主题切换,包括自定义颜色、跟随系统主题等功能。 ## 🎯 学习目标 - 使用 `IThemeService` 管理应用主题 - 实现浅色/深色主题切换 - 自定义主题颜色 - 跟随系统主题设置 - 动态主题切换(无需重启) ## 📦 使用的模块 - **Sharp.Wpf** - IThemeService, ThemeService ## 🚀 快速运行 ```bash cd examples/06-Theming dotnet run ``` ## 📝 核心代码讲解 ### 1. App.xaml.cs - 注册主题服务 ```csharp using Wpf.Theming; protected override void OnStartup(StartupEventArgs e) { var services = new ServiceCollection(); services.AddSharpWpf(); // 自动注册 IThemeService services.AddViewModel(); var provider = services.BuildServiceProvider(); // 应用初始主题 var themeService = provider.GetRequiredService(); themeService.ApplyTheme(Theme.Light); // 或 Theme.System var mainWindow = provider.GetRequiredService(); mainWindow.Show(); } ``` ### 2. MainViewModel.cs - 主题切换逻辑 ```csharp using Wpf.Theming; public class MainViewModel : ViewModelBase { private readonly IThemeService _themeService; private Theme _currentTheme; public Theme CurrentTheme { get => _currentTheme; set { SetProperty(ref _currentTheme, value); _themeService.ApplyTheme(value); } } public ICommand SwitchToLightCommand { get; } public ICommand SwitchToDarkCommand { get; } public ICommand SwitchToSystemCommand { get; } public MainViewModel(IThemeService themeService) { _themeService = themeService; _currentTheme = themeService.CurrentTheme; // 监听主题变化 _themeService.ThemeChanged += (s, theme) => { OnPropertyChanged(nameof(CurrentTheme)); }; SwitchToLightCommand = new RelayCommand(() => { CurrentTheme = Theme.Light; }); SwitchToDarkCommand = new RelayCommand(() => { CurrentTheme = Theme.Dark; }); SwitchToSystemCommand = new RelayCommand(() => { CurrentTheme = Theme.System; }); } } ``` ### 3. MainWindow.xaml - 使用主题颜色 ```xml