在C#中读取默认应用程序设置
我有自定义网格控件的许多应用程序设置(在用户范围内)。 其中大多数是颜色设置。 我有一个表单,用户可以自定义这些颜色,我想添加一个按钮,以恢复默认颜色设置。 如何阅读默认设置?
例如:
- 我在
Properties.Settings
有一个名为CellBackgroundColor
的用户设置。 - 在设计时,我使用IDE将
Color.White
的值设置为Color.White
。 - 用户在我的程序
CellBackgroundColor
Color.Black
设置为Color.Black
。 - 我使用
Properties.Settings.Default.Save()
保存设置。 - 用户单击“
Restore Default Colors
按钮。
现在, Properties.Settings.Default.CellBackgroundColor
返回Color.Black
。 我该如何回到Color.White
?
@ozgur,
Settings.Default.Properties["property"].DefaultValue // initial value from config file
例:
string foo = Settings.Default.Foo; // Foo = "Foo" by default Settings.Default.Foo = "Boo"; Settings.Default.Save(); string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo" string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
阅读“Windows 2.0 Forms Programming”,我偶然发现了这两种在这种情况下可能有用的有用方法:
ApplicationSettingsBase.Reload
ApplicationSettingsBase.Reset
来自MSDN:
重新加载与Reset形成对比,前者将加载最后一组保存的应用程序设置值,而后者将加载保存的默认值。
所以用法是:
Properties.Settings.Default.Reset() Properties.Settings.Default.Reload()
我不确定这是必要的,必须有一个更简洁的方式,否则希望有人发现这有用;
public static class SettingsPropertyCollectionExtensions { public static T GetDefault(this SettingsPropertyCollection me, string property) { string val_string = (string)Settings.Default.Properties[property].DefaultValue; return (T)Convert.ChangeType(val_string, typeof(T)); } }
用法;
var setting = Settings.Default.Properties.GetDefault("MySetting");
Properties.Settings.Default.Reset()
会将所有设置重置为其原始值。
我该如何回到Color.White?
你可以采取两种方式:
我通过2套设置解决了这个问题。 我使用Visual Studio默认为当前设置添加的那个,即Properties.Settings.Default
。 但我还在项目“项目 – >添加新项目 – >常规 – >设置文件”中添加了另一个设置文件,并将实际的默认值存储在那里,即Properties.DefaultSettings.Default
。
然后我确保我从不写入Properties.DefaultSettings.Default
设置,只需从中读取即可。 将所有内容更改回默认值只是将当前值设置回默认值的情况。
我发现调用ApplicationSettingsBase.Reset
会将设置重置为默认值,但同时也会保存它们。
我想要的行为是将它们重置为默认值但不保存它们(这样如果用户不喜欢默认值,那么在保存之前它们可以将它们还原)。
我写了一个适合我的目的的扩展方法:
上述就是C#学习教程:在C#中读取默认应用程序设置分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
using System; using System.Configuration; namespace YourApplication.Extensions { public static class ExtensionsApplicationSettingsBase { public static void LoadDefaults(this ApplicationSettingsBase that) { foreach (SettingsProperty settingsProperty in that.Properties) { that[settingsProperty.Name] = Convert.ChangeType(settingsProperty.DefaultValue, settingsProperty.PropertyType); } } } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1251055.html