ApplicationSettingsBase Classe

Définition

Agit comme classe de base pour la dérivation des classes wrapper concrètes afin d'implémenter la fonctionnalité de paramètres d'application dans les applications Windows Forms.

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
Héritage
ApplicationSettingsBase
Implémente

Exemples

L’exemple de code suivant illustre l’utilisation des paramètres d’application pour conserver les attributs suivants du formulaire main : emplacement, taille, couleur d’arrière-plan et texte de la barre de titre. Tous ces attributs sont conservés en tant que propriétés de paramètres d’application unique dans la FormSettings classe , nommées FormLocation, FormSizeet FormBackColorFormText, respectivement. Tous, à l’exception de FormText et Size sont des données liées à leurs propriétés de formulaire associées et ont une valeur de paramètre par défaut appliquée à l’aide de DefaultSettingValueAttribute.

Le formulaire contient quatre contrôles enfants qui ont les noms et fonctions suivants :

  • Bouton nommé btnBackColor utilisé pour afficher la boîte de dialogue Couleur commune.

  • Bouton nommé btnReload utilisé pour les paramètres de Reload l’application.

  • Bouton nommé btnReset utilisé pour les paramètres de Reset l’application.

  • Zone de texte nommée tbStatus utilisée pour afficher status informations sur le programme.

Notez qu’après chaque exécution de l’application, un caractère de période supplémentaire est ajouté au texte de titre du formulaire.

Cet exemple de code nécessite un formulaire avec une ColorDialog classe nommée colorDialog1et un StatusStrip contrôle avec un ToolStripStatusLabel nommé tbStatus. En outre, il nécessite trois Button objets nommés btnReload, btnResetet 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

Remarques

ApplicationSettingsBase ajoute les fonctionnalités suivantes à la SettingsBase classe, qui est utilisée par les applications web :

  • Possibilité de détecter des attributs sur une classe wrapper de paramètres dérivée. ApplicationSettingsBase prend en charge le modèle déclaratif utilisé pour les propriétés de classe wrapper, comme décrit plus loin.

  • Méthodes et Reload de niveau Save supérieur.

  • Événements de validation supplémentaires que vous pouvez gérer pour garantir l’exactitude des paramètres individuels.

Dans l’architecture des paramètres d’application, pour accéder à un groupe de propriétés de paramètres, vous devez dériver une classe wrapper concrète à partir de ApplicationSettingsBase. La classe wrapper est ApplicationSettingsBase personnalisée de la manière suivante :

  • Pour chaque propriété de paramètres à accéder, une propriété publique fortement typée correspondante est ajoutée à la classe wrapper. Cette propriété a get des accesseurs et set pour les paramètres d’application en lecture/écriture, mais uniquement un get accesseur pour les paramètres en lecture seule.

  • Les attributs appropriés doivent être appliqués aux propriétés publiques de la classe wrapper pour indiquer les caractéristiques de la propriété settings, telles que l’étendue du paramètre (application ou utilisateur), si le paramètre doit prendre en charge l’itinérance, la valeur par défaut du paramètre, le fournisseur de paramètres à utiliser, etc. Chaque propriété est requise pour spécifier son étendue, à l’aide de ApplicationScopedSettingAttribute ou UserScopedSettingAttribute. Les paramètres d’étendue de l’application sont en lecture seule si la valeur par défaut LocalFileSettingsProvider est utilisée.

La ApplicationSettingsBase classe utilise la réflexion pour détecter ces attributs au moment de l’exécution. La plupart de ces informations sont transmises à la couche du fournisseur de paramètres, qui est responsable du stockage, du format de persistance, etc.

Lorsqu’une application a plusieurs classes de wrapper de paramètres, chaque classe définit un groupe de paramètres. Chaque groupe présente les caractéristiques suivantes :

  • Un groupe peut contenir n’importe quel nombre ou type de paramètres de propriété.

  • Si le nom du groupe n’est pas défini explicitement par la décoration de la classe wrapper avec un SettingsGroupNameAttribute, un nom est généré automatiquement.

Par défaut, toutes les applications clientes utilisent le pour fournir du LocalFileSettingsProvider stockage. Si vous souhaitez utiliser un autre fournisseur de paramètres, la classe ou la propriété wrapper doit être décorée avec une valeur correspondante SettingsProviderAttribute.

Pour plus d’informations sur l’utilisation des paramètres d’application, consultez Paramètres de l’application pour Windows Forms.

Constructeurs

ApplicationSettingsBase()

Initialise une instance de la classe ApplicationSettingsBase dans son état par défaut.

ApplicationSettingsBase(IComponent)

Initialise une instance de la classe ApplicationSettingsBase à l'aide du composant propriétaire fourni.

ApplicationSettingsBase(IComponent, String)

Initialise une instance de la classe ApplicationSettingsBase à l'aide du composant propriétaire et de la clé de paramètres fournis.

ApplicationSettingsBase(String)

Initialise une instance de la classe ApplicationSettingsBase à l'aide de la clé de paramètres fournie.

Propriétés

Context

Obtient le contexte de paramètres d'application associé au groupe de paramètres.

IsSynchronized

Obtient une valeur indiquant si l'accès à l'objet est synchronisé (thread-safe).

(Hérité de SettingsBase)
Item[String]

Obtient ou définit la valeur de la propriété de paramètres d'application spécifiée.

Properties

Obtient la collection de propriétés de paramètres dans le wrapper.

PropertyValues

Obtient une collection de valeurs de propriété.

Providers

Obtient la collection de fournisseurs de paramètres d'application utilisée par le wrapper.

SettingsKey

Obtient ou définit la clé de paramètres pour le groupe de paramètres d'application.

Méthodes

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetPreviousVersion(String)

Retourne la valeur de la propriété de paramètres nommée pour la version antérieure de la même application.

GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
Initialize(SettingsContext, SettingsPropertyCollection, SettingsProviderCollection)

Initialise les propriétés internes utilisées par l'objet SettingsBase.

(Hérité de SettingsBase)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
OnPropertyChanged(Object, PropertyChangedEventArgs)

Déclenche l’événement PropertyChanged.

OnSettingChanging(Object, SettingChangingEventArgs)

Déclenche l’événement SettingChanging.

OnSettingsLoaded(Object, SettingsLoadedEventArgs)

Déclenche l’événement SettingsLoaded.

OnSettingsSaving(Object, CancelEventArgs)

Déclenche l’événement SettingsSaving.

Reload()

Actualise les valeurs de propriétés de paramètres d'application à partir du stockage persistant.

Reset()

Restaure les valeurs de paramètre d'application persistantes à leurs propriétés par défaut correspondantes.

Save()

Stocke les valeurs actuelles des propriétés de paramètres d'application.

ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)
Upgrade()

Met à jour des paramètres d'application de façon à refléter une installation plus récente de l'application.

Événements

PropertyChanged

Se produit après que la valeur d'une propriété de paramètres d'application a été modifiée.

SettingChanging

Se produit avant que la valeur d'une propriété de paramètres d'application ait été modifiée.

SettingsLoaded

Se produit après que les paramètres d'application ont été récupérés à partir du stockage.

SettingsSaving

Se produit avant que des valeurs soient enregistrées dans le magasin de données.

S’applique à

Voir aussi