在C#中读取默认的应用程序设置
时间:2020-03-05 18:49:12 来源:igfitidea点击:
我的自定义网格控件有许多应用程序设置(在用户范围内)。其中大多数是颜色设置。我有一个表单,用户可以在其中定制这些颜色,我想添加一个按钮以恢复为默认颜色设置。如何读取默认设置?
例如:
- 我在
Properties.Settings
中有一个名为CellBackgroundColor
的用户设置。 - 在设计时,我使用IDE将" CellBackgroundColor"的值设置为" Color.White"。
- 用户在我的程序中将CellBackgroundColor设置为Color.Black。
- 我用
Properties.Settings.Default.Save()
保存设置。 - 用户点击"恢复默认颜色"按钮。
现在," Properties.Settings.Default.CellBackgroundColor"将返回" Color.Black"。我该如何回到" Color.White"?
解决方案
回答
How do I go back to Color.White?
我们可以通过两种方式进行操作:
- 在用户更改设置之前,请保存设置的副本。
- 在应用程序关闭之前,缓存用户修改的设置并将其保存到Properties.Settings。
回答
@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"
回答
我有2套设置解决了这个问题。我使用Visual Studio默认为当前设置添加的内容,即" Properties.Settings.Default"。但是我还将另一个设置文件添加到我的项目"项目->添加新项目->常规->设置文件"中,并将实际的默认值存储在其中,即" Properties.DefaultSettings.Default"。
然后,我确保我永远不会写Properties.DefaultSettings.Default
设置。然后将所有内容都更改回默认值只是将当前值设置回默认值的一种情况。
回答
在阅读" Windows 2.0窗体编程"时,我偶然发现了以下两种有用的方法,在这种情况下可能会有帮助:
ApplicationSettingsBase.Reload
ApplicationSettingsBase.Reset
从MSDN:
Reload contrasts with Reset in that the former will load the last set of saved application settings values, whereas the latter will load the saved default values.
因此用法是:
Properties.Settings.Default.Reset() Properties.Settings.Default.Reload()
回答
" Properties.Settings.Default.Reset()"会将所有设置重置为其原始值。