30

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

例如:

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

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

4

7 回答 7

42

@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"
于 2008-09-08T07:55:30.397 回答
14

阅读“Windows 2.0 Forms Programming”时,我偶然发现了这两种在这种情况下可能会有所帮助的有用方法:

ApplicationSettingsBase.Reload

ApplicationSettingsBase.Reset

来自 MSDN:

Reload 与 Reset 不同,前者将加载最后一组保存的应用程序设置值,而后者将加载保存的默认值。

所以用法是:

Properties.Settings.Default.Reset()
Properties.Settings.Default.Reload()
于 2010-01-22T13:11:05.530 回答
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));
    }
}

用法;

var setting = Settings.Default.Properties.GetDefault<double>("MySetting");
于 2011-11-22T17:56:35.463 回答
3

Properties.Settings.Default.Reset()会将所有设置重置为其原始值。

于 2010-01-29T22:05:04.600 回答
2

我通过两组设置解决了这个问题。我使用 Visual Studio 默认为当前设置添加的那个,即Properties.Settings.Default. 但我还向我的项目“项目 -> 添加新项目 -> 常规 -> 设置文件”添加了另一个设置文件,并将实际的默认值存储在其中,即Properties.DefaultSettings.Default.

然后我确保我从不写入Properties.DefaultSettings.Default设置,只是从中读取。将所有内容更改回默认值只是将当前值设置回默认值的一种情况。

于 2008-09-08T08:50:20.813 回答
1

我如何回到 Color.White?

有两种方法可以做到:

  • 在用户更改设置之前保存设置的副本。
  • 在应用程序关闭之前缓存用户修改的设置并将其保存到 Properties.Settings。
于 2008-09-08T07:54:24.817 回答
1

我发现调用ApplicationSettingsBase.Reset会产生将设置重置为默认值的效果,但同时也会保存它们。

我想要的行为是将它们重置为默认值但不保存它们(这样如果用户不喜欢默认值,在它们被保存之前他们可以将它们恢复回来)。

我写了一个适合我目的的扩展方法:

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);
            }
        }
    }
}
于 2013-01-14T02:07:47.843 回答