# 设置系统 本文档介绍阑山桌面的设置系统,包括配置管理、持久化、设置页面和最佳实践。 ## 设置系统概览 阑山桌面提供了统一的设置系统,用于管理应用、插件和组件的配置数据。 ### 核心特性 - 💾 **自动持久化** - 设置自动保存到本地 - 🔔 **变更通知** - 监听设置变更事件 - 📁 **分域管理** - 按命名空间组织设置 - 🔒 **类型安全** - 泛型 API 保证类型安全 - 🎨 **UI 集成** - 轻松创建设置页面 ### 设置存储位置 ``` %LOCALAPPDATA%\LanMountainDesktop\ └── settings\ ├── app.json # 应用设置 ├── appearance.json # 外观设置 ├── plugins\ │ ├── com.example.plugin1.json │ └── com.example.plugin2.json └── components\ └── com.example.plugin1.component1.json ``` ## 使用设置服务 ### 在插件中使用 ```csharp public class MyPlugin : IPlugin { private IPluginContext? _context; public async Task InitializeAsync(IPluginContext context) { _context = context; // 通过 context 访问设置 var settings = context.Settings; // 读取设置 var apiKey = settings.GetValue("ApiKey", ""); var refreshRate = settings.GetValue("RefreshRate", 60); var enableNotifications = settings.GetValue("EnableNotifications", true); // 保存设置 settings.SetValue("LastStartTime", DateTime.Now); } } ``` ### 在组件中使用 ```csharp public class MyComponent : ComponentBase { public override Task InitializeAsync() { // 组件有自己的设置域 // 自动命名空间:{PluginId}.{ComponentId} // 读取设置 var location = Settings.GetValue("Location", "北京"); var useFahrenheit = Settings.GetValue("UseFahrenheit", false); // 读取复杂对象 var config = Settings.GetValue("Config", new ComponentConfig()); return Task.CompletedTask; } public void UpdateLocation(string location) { Location = location; // 保存设置 Settings.SetValue("Location", location); } } ``` ## 设置 API ### ISettingsService 接口 ```csharp public interface ISettingsService { /// /// 获取设置值 /// T GetValue(string key, T defaultValue); /// /// 设置值 /// void SetValue(string key, T value); /// /// 删除设置 /// void Remove(string key); /// /// 检查设置是否存在 /// bool Contains(string key); /// /// 获取所有键 /// IEnumerable GetAllKeys(); /// /// 清空所有设置 /// void Clear(); /// /// 设置变更事件 /// event EventHandler? SettingChanged; } ``` ### 基本用法 ```csharp // 读取设置 var value = settings.GetValue("Key", "DefaultValue"); // 保存设置 settings.SetValue("Key", "NewValue"); // 删除设置 settings.Remove("Key"); // 检查是否存在 if (settings.Contains("Key")) { // ... } // 获取所有键 var keys = settings.GetAllKeys(); // 清空所有设置 settings.Clear(); ``` ## 支持的数据类型 ### 基本类型 ```csharp // 字符串 settings.SetValue("Name", "张三"); var name = settings.GetValue("Name", ""); // 数字 settings.SetValue("Age", 25); var age = settings.GetValue("Age", 0); settings.SetValue("Price", 99.99); var price = settings.GetValue("Price", 0.0); // 布尔值 settings.SetValue("Enabled", true); var enabled = settings.GetValue("Enabled", false); // 日期时间 settings.SetValue("LastUpdate", DateTime.Now); var lastUpdate = settings.GetValue("LastUpdate", DateTime.MinValue); // 枚举 settings.SetValue("Theme", AppTheme.Dark); var theme = settings.GetValue("Theme", AppTheme.Light); ``` ### 复杂对象 ```csharp // 定义配置类 public class WeatherConfig { public string City { get; set; } = "北京"; public string Unit { get; set; } = "Celsius"; public int RefreshInterval { get; set; } = 10; public List FavoriteCities { get; set; } = new(); } // 保存对象 var config = new WeatherConfig { City = "上海", Unit = "Celsius", RefreshInterval = 15, FavoriteCities = new List { "北京", "上海", "广州" } }; settings.SetValue("WeatherConfig", config); // 读取对象 var savedConfig = settings.GetValue( "WeatherConfig", new WeatherConfig() ); ``` ### 集合类型 ```csharp // 列表 var favoriteColors = new List { "红色", "蓝色", "绿色" }; settings.SetValue("FavoriteColors", favoriteColors); var colors = settings.GetValue>("FavoriteColors", new List()); // 字典 var preferences = new Dictionary { ["Language"] = "zh-CN", ["Timezone"] = "Asia/Shanghai" }; settings.SetValue("Preferences", preferences); var prefs = settings.GetValue>( "Preferences", new Dictionary() ); ``` ## 监听设置变更 ### 订阅变更事件 ```csharp public class MyPlugin : IPlugin { private ISettingsService? _settings; public async Task InitializeAsync(IPluginContext context) { _settings = context.Settings; // 订阅设置变更事件 _settings.SettingChanged += OnSettingChanged; } private void OnSettingChanged(object? sender, SettingChangedEventArgs e) { // e.Key - 变更的设置键 // e.OldValue - 旧值 // e.NewValue - 新值 if (e.Key == "ApiKey") { var newApiKey = e.NewValue as string; _logger.LogInformation($"API Key changed to: {newApiKey}"); // 重新初始化服务 ReinitializeService(newApiKey); } } public async Task ShutdownAsync() { // 取消订阅(防止内存泄漏) if (_settings != null) { _settings.SettingChanged -= OnSettingChanged; } } } ``` ### 在组件中监听 ```csharp public class MyComponent : ComponentBase { public override Task InitializeAsync() { // 监听设置变更 Settings.SettingChanged += OnSettingChanged; return Task.CompletedTask; } private void OnSettingChanged(object? sender, SettingChangedEventArgs e) { switch (e.Key) { case "Location": Location = e.NewValue as string ?? "北京"; _ = RefreshWeatherAsync(); break; case "UseFahrenheit": UseFahrenheit = (bool)(e.NewValue ?? false); OnPropertyChanged(nameof(DisplayTemperature)); break; } } public override void Dispose() { // 取消订阅 Settings.SettingChanged -= OnSettingChanged; base.Dispose(); } } ``` ## 创建设置页面 ### 步骤 1: 创建设置页视图 创建 `Settings/MyPluginSettingsPage.axaml`: ```xml