You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Avalonia中如何像WPF Settings.Default那样加载和保存设置?

Avalonia 模拟旧 Properties.Settings 便捷设置方案

首先明确:KeyPerFileConfigurationProvider 不适合你的需求,它设计用于容器化环境从文件加载只读配置,无法实现本地设置的回写保存,所以不推荐使用。

针对你希望沿用 Properties.Settings.Default.xxx = yyy; Default.Save() 便捷操作的需求,可以基于官方推荐的 Microsoft.Extensions.Configuration 封装一个模拟类,完全匹配你习惯的使用方式,无需手动读写文件。

实现步骤

1. 安装依赖 NuGet 包

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.Binder

2. 创建用户配置文件

在项目中添加 appsettings.user.json 文件,设置其复制到输出目录为「如果较新则复制」,初始内容示例:

{
  "UserSettings": {
    "Theme": "Light",
    "WindowWidth": 800,
    "WindowHeight": 600
  }
}

3. 封装模拟 Settings 类

创建静态类 AppSettings,内部维护配置实例和可读写的设置属性,完全模拟旧的操作逻辑:

using Microsoft.Extensions.Configuration;
using System.IO;
using System.Text.Json;

public static class AppSettings
{
    private static IConfigurationRoot _configuration;
    // 建议将配置文件放在用户目录,避免权限问题,示例路径可根据需求修改
    private static readonly string _configPath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "YourAppName",
        "appsettings.user.json"
    );

    static AppSettings()
    {
        // 确保目录存在
        Directory.CreateDirectory(Path.GetDirectoryName(_configPath)!);
        // 如果配置文件不存在则创建默认内容
        if (!File.Exists(_configPath))
        {
            File.WriteAllText(_configPath, JsonSerializer.Serialize(new 
            { 
                UserSettings = new 
                { 
                    Theme = "Light", 
                    WindowWidth = 800, 
                    WindowHeight = 600 
                } 
            }, new JsonSerializerOptions { WriteIndented = true }));
        }

        _configuration = new ConfigurationBuilder()
            .AddJsonFile(_configPath, optional: false, reloadOnChange: true)
            .Build();
    }

    public static UserSettings Default { get; } = new UserSettings();

    public class UserSettings
    {
        // 内存缓存当前设置值
        private string _theme = _configuration["UserSettings:Theme"] ?? "Light";
        private int _windowWidth = int.TryParse(_configuration["UserSettings:WindowWidth"], out var width) ? width : 800;
        private int _windowHeight = int.TryParse(_configuration["UserSettings:WindowHeight"], out var height) ? height : 600;

        // 读取/写入设置属性
        public string Theme
        {
            get => _theme;
            set => _theme = value;
        }

        public int WindowWidth
        {
            get => _windowWidth;
            set => _windowWidth = value;
        }

        public int WindowHeight
        {
            get => _windowHeight;
            set => _windowHeight = value;
        }

        // 模拟旧的 Save() 方法,将内存中的设置写入文件
        public void Save()
        {
            var configData = JsonSerializer.Deserialize<Dictionary<string, object>>(File.ReadAllText(_configPath)) 
                             ?? new Dictionary<string, object>();

            if (!configData.ContainsKey("UserSettings"))
                configData["UserSettings"] = new Dictionary<string, object>();

            var userSettingsDict = (Dictionary<string, object>)configData["UserSettings"];
            userSettingsDict["Theme"] = _theme;
            userSettingsDict["WindowWidth"] = _windowWidth;
            userSettingsDict["WindowHeight"] = _windowHeight;

            File.WriteAllText(_configPath, JsonSerializer.Serialize(configData, new JsonSerializerOptions { WriteIndented = true }));
            
            // 重新加载配置,确保后续读取为最新值
            _configuration = new ConfigurationBuilder()
                .AddJsonFile(_configPath, optional: false, reloadOnChange: true)
                .Build();
        }
    }
}

4. 使用方式(完全匹配旧习惯)

// 读取设置
var currentTheme = AppSettings.Default.Theme;
var windowWidth = AppSettings.Default.WindowWidth;

// 修改并保存设置
AppSettings.Default.Theme = "Dark";
AppSettings.Default.WindowWidth = 1024;
AppSettings.Default.Save();

补充说明

  • 配置文件放在用户目录(SpecialFolder.ApplicationData)可以避免程序目录的权限问题,适合跨平台场景
  • 该方案基于官方推荐的配置系统,兼容Avalonia的所有平台(Windows、Linux、macOS)
  • 旧的 System.Configuration 因跨平台兼容性问题已被.NET Core/.NET 5+ 弃用,Avalonia也不再支持,因此上述封装是最贴近你需求的替代方案

内容的提问来源于stack exchange,提问作者Winfried

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:37:05