我正在编写一个使用C#作为代码的WPF应用程序,我想让用户可以选择更改我的应用程序中的某些设置。是否存在用于在应用程序中存储设置的标准,这些设置将被不断读取和写入?
答案 0 :(得分:3)
尽管app.config
文件可以写入(使用ConfigurationManager.OpenExeConfiguration
打开进行写入),但通常的做法是在那里存储只读设置。
编写简单的设置类很容易:
public sealed class Settings
{
private readonly string _filename;
private readonly XmlDocument _doc = new XmlDocument();
private const string emptyFile =
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
<appSettings>
<add key=""defaultkey"" value=""123"" />
<add key=""anotherkey"" value=""abc"" />
</appSettings>
</configuration>";
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);
}
}
/// <summary>
/// Retrieve a value by name.
/// Returns the supplied DefaultValue if not found.
/// </summary>
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;
}
/// <summary>
/// Write a config value by key
/// </summary>
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);
}
}
}
答案 1 :(得分:0)
使用ConfigurationSection
类来存储/检索配置文件
请参阅:How to: Create Custom Configuration Sections Using 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;
}
}
}
答案 2 :(得分:0)
您可以在XAML上尝试window \ page的Resources部分。