ApplicationSettingsBase 類別

定義

作為基底類別,用以推導具體包裝類別,以實作視窗表單應用程式中的應用程式設定功能。

public ref class ApplicationSettingsBase abstract : System::Configuration::SettingsBase, System::ComponentModel::INotifyPropertyChanged
public abstract class ApplicationSettingsBase : System.Configuration.SettingsBase, System.ComponentModel.INotifyPropertyChanged
type ApplicationSettingsBase = class
    inherit SettingsBase
    interface INotifyPropertyChanged
Public MustInherit Class ApplicationSettingsBase
Inherits SettingsBase
Implements INotifyPropertyChanged
繼承
ApplicationSettingsBase
實作

範例

以下程式碼範例示範如何利用應用程式設定來持久化主要表單的以下屬性:位置、大小、背景顏色及標題欄文字。 所有這些屬性都以單一應用程式設定屬性的形式在類別中 FormSettings 持續存在,分別命名為 FormLocationFormSizeFormBackColorFormText。 除了 FormTextSize 之外,所有 都綁定在其對應的表單屬性,並以 為基礎套用 DefaultSettingValueAttribute預設值。

該表單包含四個子控制項,名稱與功能如下:

  • 一個用於 btnBackColor 顯示 Color 公共對話框的按鈕。

  • 一個標示 btnReload 為應用程式設定的 Reload 按鈕。

  • 一個標示 btnReset 為應用程式設定的 Reset 按鈕。

  • 一個用於 tbStatus 顯示程式狀態資訊的文字框。

請注意,每次申請執行後,表單標題文字後會加上一個額外的句點字元。

此程式碼範例需要一個名為 ColorDialogcolorDialog1的 Form 類別,以及 StatusStrip 一個名為 ToolStripStatusLabeltbStatus的控制項。 此外,它還需要三個 Button 分別命名 btnReload為 、 btnResetbtnBackColor和 的物件。


#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
Imports System.Windows.Forms
Imports System.Drawing

Public Class Form1

    Public Shared Sub Main()

    End Sub

    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)
        DataBindings.Add(bndBackColor)
        Dim bndLocation As New Binding("Location", frmSettings1, "FormLocation",
                True, DataSourceUpdateMode.OnPropertyChanged)
        DataBindings.Add(bndLocation)

        ' Assign Size property, since databinding to Size doesn't work well.
        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
            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 = Text + "."c

        ' Save size settings manually.
        frmSettings1.FormSize = Size

        frmSettings1.Save()
    End Sub

    Private Sub btnBackColor_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnBackColor.Click
        If DialogResult.OK = colorDialog1.ShowDialog() Then
            Dim c As Color = colorDialog1.Color
            BackColor = c
        End If
    End Sub

    Private Sub btnReset_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnReset.Click
        frmSettings1.Reset()
        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 (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 被網頁應用程式所使用:

  • 能夠偵測衍生的設定包裝類別上的屬性。 ApplicationSettingsBase 支援後述用於包裝類別屬性的宣告式模型。

  • 更高層次 SaveReload 方法。

  • 你可以處理額外的驗證事件,以確保個別設定的正確性。

在應用程式設定架構中,若要存取一組設定屬性,你需要從 ApplicationSettingsBase中推導出一個具體的包裝類別。 包裝類別可透過以下方式進行 ApplicationSettingsBase 客製化:

  • 每存取一個 settings 屬性,包裝類別中都會加入一個對應的強型別公共屬性。 此屬性有 getset 的 存取器用於讀取/寫入應用程式的設定,但僅有一個 get 存取器用於唯讀設定。

  • 必須套用適當的屬性到包裝類別的公開屬性,以指示設定屬性的特性,例如設定的範圍(應用程式或使用者)、設定是否應支援漫遊、設定的預設值、所使用的設定提供者等等。 每個屬性都必須指定其作用域,使用或 ApplicationScopedSettingAttributeUserScopedSettingAttribute。 若使用預設 LocalFileSettingsProvider 值,應用程式範圍設定為唯讀。

ApplicationSettingsBase 類別在執行時會利用反射來偵測這些屬性。 大部分資訊會傳遞到設定提供者層,負責儲存、持久化格式等。

當應用程式有多個設定包裝類別時,每個類別會定義一個 設定群組。 每個群體具有以下特徵:

  • 一個群組可以包含任意數量或類型的屬性設定。

  • 若群組名稱未由包裝類別 SettingsGroupNameAttribute的裝飾中明確設定,則會自動產生名稱。

預設情況下,所有用戶端應用程式都使用 以 LocalFileSettingsProvider 提供儲存空間。 若需要替代設定提供者,則包裝類別或屬性必須以對應 SettingsProviderAttribute的 。

欲了解更多使用應用程式設定的資訊,請參閱 Windows Forms<>c0>Application Settings 的<。

建構函式

名稱 Description
ApplicationSettingsBase()

將類別的實例 ApplicationSettingsBase 初始化為預設狀態。

ApplicationSettingsBase(IComponent, String)

使用提供的擁有者元件與設定鍵初始化類別實例 ApplicationSettingsBase

ApplicationSettingsBase(IComponent)

使用所提供的擁有者元件初始化該 ApplicationSettingsBase 類別的實例。

ApplicationSettingsBase(String)

使用提供的設定鍵初始化類別實例 ApplicationSettingsBase

屬性

名稱 Description
Context

它會取得與設定群組相關聯的應用程式設定上下文。

IsSynchronized

會取得一個值,表示對物件的存取是否同步(執行緒安全)。

(繼承來源 SettingsBase)
Item[String]

取得或設定指定的應用程式設定屬性值。

Properties

會取得包裝器中設定屬性的集合。

PropertyValues

會獲得一系列房產價值。

Providers

取得包裝器所使用的應用程式設定提供者集合。

SettingsKey

取得或設定應用程式設定群組的設定鍵。

方法

名稱 Description
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()

更新應用程式設定以反映較新的應用程式安裝。

事件

名稱 Description
PropertyChanged

發生在更改應用程式設定屬性的值之後。

SettingChanging

發生在更改應用程式設定屬性值之前。

SettingsLoaded

發生在從儲存裝置取出應用程式設定之後。

SettingsSaving

發生在數值儲存到資料儲存之前。

適用於

另請參閱