在C#中读取默认应用程序设置

Ozg*_*tak 28 .net c# application-settings winforms

我有自定义网格控件的许多应用程序设置(在用户范围内).其中大多数是颜色设置.我有一个表单,用户可以自定义这些颜色,我想添加一个按钮,以恢复默认颜色设置.如何阅读默认设置?

例如:

  1. 我有一个名为用户设置CellBackgroundColorProperties.Settings.
  2. 在设计时我将值设置CellBackgroundColorColor.White使用IDE.
  3. 用户设置CellBackgroundColorColor.Black在我的计划.
  4. 我保存设置Properties.Settings.Default.Save().
  5. 用户点击Restore Default Colors按钮.

现在,Properties.Settings.Default.CellBackgroundColor回归Color.Black.我怎么回去Color.White

aku*_*aku 39

@ozgur,

Settings.Default.Properties["property"].DefaultValue // initial value from config file
Run Code Online (Sandbox Code Playgroud)

例:

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"
Run Code Online (Sandbox Code Playgroud)


Oha*_*der 12

阅读"Windows 2.0 Forms Programming",我偶然发现了这两种在这种情况下可能有用的有用方法:

ApplicationSettingsBase.Reload

ApplicationSettingsBase.Reset

来自MSDN:

重新加载与Reset形成对比,前者将加载最后一组保存的应用程序设置值,而后者将加载保存的默认值.

所以用法是:

Properties.Settings.Default.Reset()
Properties.Settings.Default.Reload()
Run Code Online (Sandbox Code Playgroud)


exp*_*boy 5

我不是很确定这是必要的,必须有一个更整洁的方法,否则希望有人觉得这有用。

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

用法;

var setting = Settings.Default.Properties.GetDefault<double>("MySetting");
Run Code Online (Sandbox Code Playgroud)