ApplicationSettingsBase 类  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
作为派生具体包装类以实现 Window 窗体应用程序中的应用程序设置功能的基类。
public ref class ApplicationSettingsBase abstract : System::Configuration::SettingsBase, System::ComponentModel::INotifyPropertyChangedpublic abstract class ApplicationSettingsBase : System.Configuration.SettingsBase, System.ComponentModel.INotifyPropertyChangedtype ApplicationSettingsBase = class
    inherit SettingsBase
    interface INotifyPropertyChangedPublic MustInherit Class ApplicationSettingsBase
Inherits SettingsBase
Implements INotifyPropertyChanged- 继承
- 实现
示例
下面的代码示例演示了如何使用应用程序设置来保留main窗体的以下属性:位置、大小、背景色和标题栏文本。 所有这些属性都作为单个应用程序设置属性保留在 类中FormSettings,分别名为 FormLocation、 FormSizeFormBackColor 和 FormText。 除 和 Size 之外FormText的所有数据都绑定到其关联的表单属性,并且使用 DefaultSettingValueAttribute应用了默认设置值。
窗体包含四个具有以下名称和函数的子控件:
- 一个名为 的 - btnBackColor按钮,用于显示“ 颜色 通用”对话框。
- 用于Reload应用程序设置的名为 - btnReload的按钮。
- 用于Reset应用程序设置的名为 - btnReset的按钮。
- 名为 的 - tbStatus文本框,用于显示有关程序的状态信息。
请注意,每次执行应用程序后,窗体的标题文本中会追加一个额外的句点字符。
此代码示例需要具有名为 的colorDialog1类的 FormColorDialog,以及具有StatusStrip名为 的ToolStripStatusLabeltbStatus控件。 此外,它需要三 Button 个名为 btnReload、 btnReset和 btnBackColor的对象。
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::Drawing;
using namespace System::Configuration;
using namespace System::Windows::Forms;
namespace AppSettingsSample
{
    //Application settings wrapper class
    ref class FormSettings sealed: public ApplicationSettingsBase
    {
    public:
        [UserScopedSettingAttribute()]
        property String^ FormText
        {
            String^ get()
            {
                return (String^)this["FormText"];
            }
            void set( String^ value )
            {
                this["FormText"] = value;
            }
        }
    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("0, 0")]
        property Point FormLocation
        {
            Point get()
            {
                return (Point)(this["FormLocation"]);
            }
            void set( Point value )
            {
                this["FormLocation"] = value;
            }
        }
    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("225, 200")]
        property Size FormSize
        {
            Size get()
            {
                return (Size)this["FormSize"];
            }
            void set( Size value )
            {
                this["FormSize"] = value;
            }
        }
    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("LightGray")]
        property Color FormBackColor
        {
            Color get()
            {
                return (Color)this["FormBackColor"];
            }
            void set(Color value)
            {
                this["FormBackColor"] = value;
            }
        }
    };
    ref class AppSettingsForm : Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
    private:
        System::ComponentModel::IContainer^ components;
        /// <summary>
        /// Clean up any resources being used. The Dispose(true) 
        /// pattern for embedded objects is implemented with this
        /// code that just contains a destructor 
        /// </summary>
    public:
        ~AppSettingsForm()
        {
            if (components != nullptr)
            {
                delete components;
            }
        }
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
    private:
        void InitializeComponent()
        {
            this->components = nullptr;
            this->colorDialog = gcnew System::Windows::Forms::ColorDialog();
            this->backColorButton = gcnew System::Windows::Forms::Button();
            this->resetButton = gcnew System::Windows::Forms::Button();
            this->statusDisplay = gcnew System::Windows::Forms::TextBox();
            this->reloadButton = gcnew System::Windows::Forms::Button();
            this->SuspendLayout();
            //
            // backColorButton
            //
            this->backColorButton->Location = System::Drawing::Point(26, 24);
            this->backColorButton->Name = "backColorButton";
            this->backColorButton->Size = System::Drawing::Size(159, 23);
            this->backColorButton->TabIndex = 0;
            this->backColorButton->Text = "Change Background Color";
            this->backColorButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::BackColorButton_Click);
            //
            // resetButton
            //
            this->resetButton->Location = System::Drawing::Point(26, 90);
            this->resetButton->Name = "resetButton";
            this->resetButton->Size = System::Drawing::Size(159, 23);
            this->resetButton->TabIndex = 1;
            this->resetButton->Text = "Reset to Defaults";
            this->resetButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::ResetButton_Click);
            //
            // statusDisplay
            //
            this->statusDisplay->Location = System::Drawing::Point(26, 123);
            this->statusDisplay->Name = "statusDisplay";
            this->statusDisplay->Size = System::Drawing::Size(159, 20);
            this->statusDisplay->TabIndex = 2;
            //
            // reloadButton
            //
            this->reloadButton->Location = System::Drawing::Point(26, 57);
            this->reloadButton->Name = "reloadButton";
            this->reloadButton->Size = System::Drawing::Size(159, 23);
            this->reloadButton->TabIndex = 3;
            this->reloadButton->Text = "Reload from Storage";
            this->reloadButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::ReloadButton_Click);
            //
            // AppSettingsForm
            //
            this->ClientSize = System::Drawing::Size(217, 166);
            this->Controls->Add(this->reloadButton);
            this->Controls->Add(this->statusDisplay);
            this->Controls->Add(this->resetButton);
            this->Controls->Add(this->backColorButton);
            this->Name = "AppSettingsForm";
            this->Text = "App Settings";
            this->FormClosing += gcnew
                System::Windows::Forms::FormClosingEventHandler
                (this,&AppSettingsForm::AppSettingsForm_FormClosing);
            this->Load += gcnew System::EventHandler(this,
                &AppSettingsForm::AppSettingsForm_Load);
            this->ResumeLayout(false);
            this->PerformLayout();
        }
#pragma endregion
    private:
        System::Windows::Forms::ColorDialog^ colorDialog;
        System::Windows::Forms::Button^ backColorButton;
        System::Windows::Forms::Button^ resetButton;
        System::Windows::Forms::TextBox^ statusDisplay;
        System::Windows::Forms::Button^ reloadButton;
        FormSettings ^ formSettings;
    public:
        AppSettingsForm()
        {
            formSettings = gcnew FormSettings;
            InitializeComponent();
        }
    private:
        void AppSettingsForm_Load(Object^ sender, EventArgs^ e)
        {
            //Associate settings property event handlers.
            formSettings->SettingChanging += gcnew SettingChangingEventHandler(
                this, &AppSettingsForm::FormSettings_SettingChanging);
            formSettings->SettingsSaving += gcnew SettingsSavingEventHandler(
                this,&AppSettingsForm::FormSettings_SettingsSaving);
            //Data bind settings properties with straightforward associations.
            Binding^ backColorBinding = gcnew Binding("BackColor", 
                formSettings, "FormBackColor", true, 
                DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(backColorBinding);
            Binding^ sizeBinding = gcnew Binding("Size", formSettings,
                "FormSize", true, DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(sizeBinding);
            Binding^ locationBinding = gcnew Binding("Location", formSettings,
                "FormLocation", true, DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(locationBinding);
            //For more complex associations, manually assign associations.
            String^ savedText = formSettings->FormText;
            //Since there is no default value for FormText.
            if (savedText != nullptr)
            {
                this->Text = savedText;
            }
        }
    private:
        void AppSettingsForm_FormClosing(Object^ sender,
            FormClosingEventArgs^ e)
        {
            //Synchronize manual associations first.
            formSettings->FormText = this->Text + '.';
            formSettings->Save();
        }
    private:
        void BackColorButton_Click(Object^ sender, EventArgs^ e)
        {
            if (::DialogResult::OK == colorDialog->ShowDialog())
            {
                Color color = colorDialog->Color;
                this->BackColor = color;
            }
        }
    private:
        void ResetButton_Click(Object^ sender, EventArgs^ e)
        {
            formSettings->Reset();
            this->BackColor = SystemColors::Control;
        }
    private:
        void ReloadButton_Click(Object^ sender, EventArgs^ e)
        {
            formSettings->Reload();
        }
    private:
        void FormSettings_SettingChanging(Object^ sender,
            SettingChangingEventArgs^ e)
        {
            statusDisplay->Text = e->SettingName + ": " + e->NewValue;
        }
    private:
        void FormSettings_SettingsSaving(Object^ sender,
            CancelEventArgs^ e)
        {
            //Should check for settings changes first.
            ::DialogResult^ dialogResult = MessageBox::Show(
                "Save current values for application settings?",
                "Save Settings", MessageBoxButtons::YesNo);
            if (::DialogResult::No == dialogResult)
            {
                e->Cancel = true;
            }
        }
    };
partial class Form1 : Form
{
    private FormSettings frmSettings1 = new FormSettings();
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
        //Associate settings property event handlers.
        frmSettings1.SettingChanging += new SettingChangingEventHandler(
                                            frmSettings1_SettingChanging);
        frmSettings1.SettingsSaving += new SettingsSavingEventHandler(
                                            frmSettings1_SettingsSaving);
        //Data bind settings properties with straightforward associations.
        Binding bndBackColor = new Binding("BackColor", frmSettings1,
            "FormBackColor", true, DataSourceUpdateMode.OnPropertyChanged);
        this.DataBindings.Add(bndBackColor);
        Binding bndLocation = new Binding("Location", frmSettings1,
            "FormLocation", true, DataSourceUpdateMode.OnPropertyChanged);
        this.DataBindings.Add(bndLocation);
        // Assign Size property, since databinding to Size doesn't work well.
         this.Size = frmSettings1.FormSize;
        //For more complex associations, manually assign associations.
        String savedText = frmSettings1.FormText;
        //Since there is no default value for FormText.
        if (savedText != null)
            this.Text = savedText;
    }
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Synchronize manual associations first.
        frmSettings1.FormText = this.Text + '.';
        frmSettings1.FormSize = this.Size;
        frmSettings1.Save();
    }
    private void btnBackColor_Click(object sender, EventArgs e)
    {
        if (DialogResult.OK == colorDialog1.ShowDialog())
        {
            Color c = colorDialog1.Color;
            this.BackColor = c;
        }
    }
    private void btnReset_Click(object sender, EventArgs e)
    {
        frmSettings1.Reset();
        this.BackColor = SystemColors.Control;
    }
    private void btnReload_Click(object sender, EventArgs e)
    {
        frmSettings1.Reload();
    }
    void frmSettings1_SettingChanging(object sender, SettingChangingEventArgs e)
    {
        tbStatus.Text = e.SettingName + ": " + e.NewValue;
    }
    void frmSettings1_SettingsSaving(object sender, CancelEventArgs e)
    {
        //Should check for settings changes first.
        DialogResult dr = MessageBox.Show(
                        "Save current values for application settings?",
                        "Save Settings", MessageBoxButtons.YesNo);
        if (DialogResult.No == dr)
        {
            e.Cancel = true;
        }
    }
}
//Application settings wrapper class
sealed class FormSettings : ApplicationSettingsBase
{
    [UserScopedSettingAttribute()]
    public String FormText
    {
        get { return (String)this["FormText"]; }
        set { this["FormText"] = value; }
    }
    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("0, 0")]
    public Point FormLocation
    {
        get { return (Point)(this["FormLocation"]); }
        set { this["FormLocation"] = value; }
    }
    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("225, 200")]
    public Size FormSize
    {
        get { return (Size)this["FormSize"]; }
        set { this["FormSize"] = value; }
    }
    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("LightGray")]
    public Color FormBackColor
    {
        get { return (Color)this["FormBackColor"]; }
        set { this["FormBackColor"] = value; }
    }
}
Imports System.Configuration
Imports System.ComponentModel
Public Class Form1
    Private WithEvents frmSettings1 As New FormSettings
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
            Handles MyBase.Load
        'Settings property event handlers are associated through WithEvents 
        '  and Handles combination.
        'Data bind settings properties with straightforward associations.
        Dim bndBackColor As New Binding("BackColor", frmSettings1, "FormBackColor", _
                True, DataSourceUpdateMode.OnPropertyChanged)
        Me.DataBindings.Add(bndBackColor)
        Dim bndLocation As New Binding("Location", frmSettings1, "FormLocation", _
                True, DataSourceUpdateMode.OnPropertyChanged)
        Me.DataBindings.Add(bndLocation)
        ' Assign Size property, since databinding to Size doesn't work well.
        Me.Size = frmSettings1.FormSize
        'For more complex associations, manually assign associations.
        Dim savedText As String = frmSettings1.FormText
        'Since there is no default value for FormText.
        If (savedText IsNot Nothing) Then
            Me.Text = savedText
        End If
    End Sub
    Private Sub Form1_FormClosing_1(ByVal sender As Object, ByVal e As _
            FormClosingEventArgs) Handles MyBase.FormClosing
        'Synchronize manual associations first.
        frmSettings1.FormText = Me.Text + "."c
        ' Save size settings manually.
        frmSettings1.FormSize = Me.Size
        frmSettings1.Save()
    End Sub
    Private Sub btnBackColor_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnBackColor.Click
        If System.Windows.Forms.DialogResult.OK = colorDialog1.ShowDialog() Then
            Dim c As Color = colorDialog1.Color
            Me.BackColor = c
        End If
    End Sub
    Private Sub btnReset_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnReset.Click
        frmSettings1.Reset()
        Me.BackColor = SystemColors.Control
    End Sub
    Private Sub btnReload_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnReload.Click
        frmSettings1.Reload()
    End Sub
    Private Sub frmSettings1_SettingChanging(ByVal sender As Object, ByVal e As _
            SettingChangingEventArgs) Handles frmSettings1.SettingChanging
        tbStatus.Text = e.SettingName & ": " & e.NewValue.ToString
    End Sub
    Private Sub frmSettings1_SettingsSaving(ByVal sender As Object, ByVal e As _
            CancelEventArgs) Handles frmSettings1.SettingsSaving
        'Should check for settings changes first.
        Dim dr As DialogResult = MessageBox.Show( _
            "Save current values for application settings?", "Save Settings", _
            MessageBoxButtons.YesNo)
        If (System.Windows.Forms.DialogResult.No = dr) Then
            e.Cancel = True
        End If
    End Sub
End Class
'Application settings wrapper class. This class defines the settings we intend to use in our application.
NotInheritable Class FormSettings
    Inherits ApplicationSettingsBase
    <UserScopedSettingAttribute()> _
    Public Property FormText() As String
        Get
            Return CStr(Me("FormText"))
        End Get
        Set(ByVal value As String)
            Me("FormText") = value
        End Set
    End Property
    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("0, 0")> _
    Public Property FormLocation() As Point
        Get
            Return CType(Me("FormLocation"), Point)
        End Get
        Set(ByVal value As Point)
            Me("FormLocation") = value
        End Set
    End Property
    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("225, 200")> _
    Public Property FormSize() As Size
        Get
            Return CType(Me("FormSize"), Size)
        End Get
        Set(ByVal value As Size)
            Me("FormSize") = value
        End Set
    End Property
    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("LightGray")> _
    Public Property FormBackColor() As Color
        Get
            Return CType(Me("FormBackColor"), Color)
        End Get
        Set(ByVal value As Color)
            Me("FormBackColor") = value
        End Set
    End Property
End Class
注解
ApplicationSettingsBase 将以下功能添加到 SettingsBase 类,该类由基于 Web 的应用程序使用:
- 检测派生的设置包装器类的属性的功能。 ApplicationSettingsBase 支持用于包装类属性的声明性模型,如后文所述。 
- 可以处理的其他验证事件,以确保各个设置的正确性。 
在应用程序设置体系结构中,若要访问一组设置属性,需要从 ApplicationSettingsBase派生一个具体的包装类。 包装类通过以下方式进行自定义 ApplicationSettingsBase :
- 对于要访问的每个设置属性,会将相应的强类型公共属性添加到包装类。 此属性具有 - get用于读/写应用程序设置的 和- set访问器,但只有- get用于只读设置的访问器。
- 必须向包装类的公共属性应用适当的属性,以指示设置属性的特征,例如设置的范围 (应用程序或用户) 、设置是否应支持漫游、设置的默认值、要使用的设置提供程序等。 每个属性都需要使用 ApplicationScopedSettingAttribute 或 UserScopedSettingAttribute指定其范围。 如果使用默认值 LocalFileSettingsProvider ,则应用程序范围的设置是只读的。 
类 ApplicationSettingsBase 使用反射在运行时检测这些属性。 大部分此信息会传递到设置提供程序层,该层负责存储、持久性格式等。
当应用程序具有多个设置包装类时,每个类定义一个 设置组。 每个组具有以下特征:
- 组可以包含任意数量或类型的属性设置。 
- 如果使用 修饰包装类 SettingsGroupNameAttribute未显式设置组名称,则自动生成名称。 
默认情况下,所有基于客户端的应用程序都使用 LocalFileSettingsProvider 提供存储。 如果需要备用设置提供程序,则必须使用相应的 SettingsProviderAttribute修饰包装类或属性。
有关使用应用程序设置的详细信息,请参阅Windows 窗体的应用程序设置。
构造函数
| ApplicationSettingsBase() | 将 ApplicationSettingsBase 类的实例初始化为其默认状态。 | 
| ApplicationSettingsBase(IComponent) | 使用提供的所有者组件初始化 ApplicationSettingsBase 类的实例。 | 
| ApplicationSettingsBase(IComponent, String) | 使用提供的所有者组件和设置键初始化 ApplicationSettingsBase 类的实例。 | 
| ApplicationSettingsBase(String) | 使用提供的设置键初始化 ApplicationSettingsBase 类的实例。 | 
属性
| Context | 获取与设置组关联的应用程序设置上下文。 | 
| IsSynchronized | 获取一个值,该值指示访问对象是否同步(线程安全)。(继承自 SettingsBase) | 
| Item[String] | 获取或设置指定的应用程序设置属性的值。 | 
| Properties | 获取包装中的设置属性的集合。 | 
| PropertyValues | 获取属性值的集合。 | 
| Providers | 获取包装所使用的应用程序设置提供程序的集合。 | 
| SettingsKey | 获取或设置应用程序设置组的设置键。 | 
方法
| Equals(Object) | 确定指定对象是否等于当前对象。(继承自 Object) | 
| GetHashCode() | 作为默认哈希函数。(继承自 Object) | 
| GetPreviousVersion(String) | 返回同一应用程序的早期版本的命名设置属性的值。 | 
| GetType() | 获取当前实例的 Type。(继承自 Object) | 
| Initialize(SettingsContext, SettingsPropertyCollection, SettingsProviderCollection) | 初始化 SettingsBase 对象使用的内部属性。(继承自 SettingsBase) | 
| MemberwiseClone() | 创建当前 Object 的浅表副本。(继承自 Object) | 
| OnPropertyChanged(Object, PropertyChangedEventArgs) | 引发 PropertyChanged 事件。 | 
| OnSettingChanging(Object, SettingChangingEventArgs) | 引发 SettingChanging 事件。 | 
| OnSettingsLoaded(Object, SettingsLoadedEventArgs) | 引发 SettingsLoaded 事件。 | 
| OnSettingsSaving(Object, CancelEventArgs) | 引发 SettingsSaving 事件。 | 
| Reload() | 从永久存储刷新应用程序设置属性值。 | 
| Reset() | 将保持的应用程序设置值还原为其对应的默认属性。 | 
| Save() | 存储应用程序设置属性的当前值。 | 
| ToString() | 返回表示当前对象的字符串。(继承自 Object) | 
| Upgrade() | 更新应用程序设置,以反映最近安装的应用程序。 | 
事件
| PropertyChanged | 发生在更改应用程序设置属性的值之后。 | 
| SettingChanging | 发生在更改应用程序设置属性的值之前。 | 
| SettingsLoaded | 在从存储区中检索应用程序设置之后发生。 | 
| SettingsSaving | 发生在将值保存到数据存储区中之前。 |