我正在用C#編寫WPF應用程序作爲背後的代碼,我想讓用戶可以選擇更改我的應用程序中的某些設置。在應用程序中存儲設置的標準是否會不斷被讀取和寫入?WPF應用程序設置文件
1
A
回答
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);
}
}
}
0
使用ConfigurationSection
類來存儲/檢索配置文件設置
見:How to: Create Custom Configuration Sections Using ConfigurationSection
public class ColorElement : ConfigurationElement
{
[ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)]
[StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]
public String Background
{
get
{
return (String)this["background"];
}
set
{
this["background"] = value;
}
}
}
0
你可以試試窗口\ XAML的資源部分。
相關問題
- 1. 如何創建設置文件從WPF應用程序
- 2. 開發WPF應用程序,如Windows 10設置應用程序
- 3. 爲Android應用程序設置文件
- 4. 如何在WPF應用程序中全局設置文化?
- 5. WPF應用程序清單文件
- 6. 從WPF應用程序上傳文件
- 7. 多線程wpf應用程序設置線程cultureinfo
- 8. 在設置應用程序中創建應用程序設置
- 9. 漫遊配置文件的應用程序/用戶設置
- 10. WPF應用程序設置 - 重置一個屬性
- 11. C#WPF應用程序.NET 4.5設置鼠標位置
- 12. 在WPF C#應用程序中設置默認值的位置?
- 13. 重新編譯WPF應用程序的配置文件?
- 14. 在wpf web應用程序中加載配置文件
- 15. C# - 應用程序配置文件 - 自定義設置
- 16. springboot應用程序:如何設置配置文件propery與spel?
- 17. 更改應用程序設置文件的存儲位置
- 18. 讓iOS設置配置文件應用程序過期
- 19. 從XML文件讀取Gtk3應用程序的配置設置
- 20. 通過XML文件配置的Linux C++應用程序設置
- 21. 不能設置應用程序設置
- 22. 在WPF項目中啓用應用程序框架設置?
- 23. 大型應用程序設計(WPF/Silverlight)
- 24. 基於PSD設計WPF應用程序
- 25. 設置應用程序Xcode
- 26. Django設置應用程序?
- 27. Facebook應用程序設置
- 28. 設置Facebook應用程序?
- 29. C#應用程序設置
- 30. 設置AngularUi應用程序