我有自定义网格控件的许多应用程序设置(在用户范围内)。 其中大多数是颜色设置。 我有一个表单,用户可以自定义这些颜色,我想添加一个按钮,以恢复默认颜色设置。 如何阅读默认设置?
例如:
我在Properties.Settings中有一个名为CellBackgroundColor的用户设置。
在设计时,我使用IDE将CellBackgroundColor的值设置为Color.White。
用户在我的程序中将CellBackgroundColor设置为Color.Black。
我用Properties.Settings.Default.Save()保存设置。
用户单击Restore Default Colors按钮。
现在,Properties.Settings.Default.CellBackgroundColor返回Color.Black。 我该如何回到Color.White?
@ozgur,
1
| Settings.Default.Properties["property"].DefaultValue // initial value from config file |
例:
1 2 3 4 5
| 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:
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.
所以用法是:
1 2
| Properties.Settings.Default.Reset()
Properties.Settings.Default.Reload() |
我不确定这是否必要,必须有一个更简洁的方式,否则希望有人发现这有用;
1 2 3 4 5 6 7 8 9
| public static class SettingsPropertyCollectionExtensions
{
public static T GetDefault< T >(this SettingsPropertyCollection me, string property)
{
string val_string = (string)Settings.Default.Properties[property].DefaultValue;
return (T)Convert.ChangeType(val_string, typeof(T));
}
} |
用法;
1
| var setting = Settings.Default.Properties.GetDefault<double>("MySetting"); |
Properties.Settings.Default.Reset()会将所有设置重置为原始值。
我通过设置2组来解决这个问题。我使用Visual Studio默认为当前设置添加的那个,即Properties.Settings.Default。但我还在项目"项目 - >添加新项目 - >常规 - >设置文件"中添加了另一个设置文件,并将实际的默认值存储在那里,即Properties.DefaultSettings.Default。
然后我确保我从不写Properties.DefaultSettings.Default设置,只是从中读取。将所有内容更改回默认值只是将当前值设置回默认值的情况。
我发现调用ApplicationSettingsBase.Reset会将设置重置为默认值,但同时也会保存它们。
我想要的行为是将它们重置为默认值但不保存它们(这样如果用户不喜欢默认值,那么在保存之前它们可以将它们还原)。
我写了一个适合我的目的的扩展方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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);
}
}
}
} |
How do I go back to Color.White?
你可以采取两种方式:
-
在用户更改之前保存设置的副本。
-
在应用程序关闭之前,缓存用户修改的设置并将其保存到Properties.Settings。