Configuring Application/User Settings in WPF the easy way.

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Thu, 17 Jun 2010 15:40:08 GMT Indexed on 2010/06/17 22:54 UTC
Read the original article Hit count: 352

Filed under:

In this tutorial, we are going to configure the application/user settings in a WPF application the easy way. Most example that I’ve seen on the net involve the ConfigurationManager class and involve creating your own XML file from scratch. I am going to show you a easier way to do it. (in my humble opinion)

First, the definitions:

User Setting – is designed to be something specific to the user. For example, one user may have a requirement to see certain stocks, news articles or local weather. This can be set at run-time.

Application Setting – is designed to store information such as a database connection string. These settings are read-only at run-time.

1) Lets create a new WPF Project and play with a few settings. Once you are inside VS, then paste the following code snippet inside the <Grid> tags.

    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,11,0,0" Name="textBox1" VerticalAlignment="Top" Width="285" Grid.ColumnSpan="2" />
        <Button Content="Set Title" Name="button2" Click="button2_Click" Margin="108,40,96,114" />
        <TextBlock Height="23" Name="textBlock1" Text="TextBlock" VerticalAlignment="Bottom" Width="377" />
    </Grid>

Basically, its just a Textbox, Button and TextBlock. The main Window should look like the following:

image

 

2) Now we are going to setup our Configuration Settings. Look in the Solution Explorer and double click on the Settings.settings file. Make sure that your settings file looks just like mine included below:

 image

What just happened was the designer created an XML file and created the Settings.Designer.cs file which looks like this:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WPFExam.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("ApplicationName")]
        public string ApplicationName {
            get {
                return ((string)(this["ApplicationName"]));
            }
            set {
                this["ApplicationName"] = value;
            }
        }
        
        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("SQL_SRV342")]
        public string DatabaseServerName {
            get {
                return ((string)(this["DatabaseServerName"]));
            }
        }
    }
}

The XML File is named app.config and looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <WPFExam.Properties.Settings>
            <setting name="ApplicationName" serializeAs="String">
                <value>ApplicationName</value>
            </setting>
        </WPFExam.Properties.Settings>
    </userSettings>
    <applicationSettings>
        <WPFExam.Properties.Settings>
            <setting name="DatabaseServerName" serializeAs="String">
                <value>SQL_SRV342</value>
            </setting>
        </WPFExam.Properties.Settings>
    </applicationSettings>
</configuration>

3) The only left now is the code behind the button. Double click the button and replace the MainWindow() method with the following code snippet.

        public MainWindow()
        {
            InitializeComponent();
            this.Title = Properties.Settings.Default.ApplicationName;
            textBox1.Text = Properties.Settings.Default.ApplicationName;
            textBlock1.Text = Properties.Settings.Default.DatabaseServerName;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.ApplicationName = textBox1.Text.ToString();
            Properties.Settings.Default.Save();
        }

Run the application and type something in the textbox and hit the Set Title button. Now, restart the application and you should see the text that you entered earlier.

 

image

If you look at the button2 click event, you will see that it was actually 2 lines of codes to save to the configuration file. I hope this helps, for more information consult MSDN.

© Geeks with Blogs or respective owner