WPF应用程序设置文件
我正在编写一个使用C#作为代码的WPF应用程序,我想让用户可以选择更改我的应用程序中的某些设置。 是否存在用于在应用程序中存储设置的标准,该标准将被不断读取和写入?
尽管可以写入app.config
文件(使用ConfigurationManager.OpenExeConfiguration
打开以进行写入),但通常的做法是在其中存储只读设置。
编写简单的设置类很容易:
public sealed class Settings { private readonly string _filename; private readonly XmlDocument _doc = new XmlDocument(); private const string emptyFile = @" "; public Settings(string path, string filename) { // strip any trailing backslashes... while (path.Length > 0 && path.EndsWith("\\")) { path = path.Remove(path.Length - 1, 1); } _filename = Path.Combine(path, filename); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(_filename)) { // Create it... _doc.LoadXml(emptyFile); _doc.Save(_filename); } else { _doc.Load(_filename); } } /// /// Retrieve a value by name. /// Returns the supplied DefaultValue if not found. /// public string Get(string key, string defaultValue) { XmlNode node = _doc.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']"); if (node == null) { return defaultValue; } return node.Attributes["value"].Value ?? defaultValue; } /// /// Write a config value by key /// public void Set(string key, string value) { XmlNode node = _doc.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']"); if (node != null) { node.Attributes["value"].Value = value; _doc.Save(_filename); } } }
使用ConfigurationSection
类来存储/检索配置文件中的设置
请参阅: 如何:使用ConfigurationSection创建自定义配置节
public class ColorElement : ConfigurationElement { [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)] public String Background { get { return (String)this["background"]; } set { this["background"] = value; } } }
您可以在XAML上尝试window \ page的Resources部分。