User Settings in WPF

It's been a while since my last post, so I figured I'd write something I just recently had to work on: user settings.

In many client applications, you quickly run into the need to store application or user settings. There are a few options on how to do that, some of which are more complex than others, and I'll provide links at the end on a other options I found. In this post, I'll describe one of the simpler solutions, which takes advantage of existing functionality in Visual Studio, makes use of data-binding in Xaml, and also allows you to retrieve or set settings through code.

Visual Studio has design-time support for application and user settings, described quite well in the MSDN documentation. The VS designer creates as Settings class and automatically generates properties based on the setting names. Moreover, the settings will work in a ClickOnce application. As for the limitations mentioned in the article, I would add that design-time implies you need to know the user settings ahead of time. Not usually a big problem, but it can be for more complex scenarios. For example, if your application supports plug-ins that have custom settings, you wouldn't necessarily know this ahead of time.

Assuming you’ve already created settings for your application, how could you go about making use of them in a WPF application? In order to access the properties in Xaml, you could add an entry in the application's resource dictionary:

<Application x:Class="SampleApp.App"
   xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:properties="clr-namespace:SampleApp.Properties"
   Exit="OnExit"
   StartupUri="MainWindow.xaml">
     <Application.Resources>
         <properties:Settings x:Key="Settings" />
     </Application.Resources>
</Application>

If you had added a setting named Username as a string type, you could bind a TextBox in Xaml this way:

<TextBox Text="{Binding Source={StaticResource Settings}, Path=Default.Username}" />

As you enter text in the TextBox, the two-way binding automatically updates the Username setting, and similarly at startup, the TextBox will be populated with the most recently saved Username value.

Finally, in order to ensure your settings are properly saved, you could implement the OnExit handler declared above, or alternatively you could put the settings in a dedicated window and save at the appropriate time.

private void OnExit(object sender, ExitEventArgs e)
{
    Properties.Settings.Default.Save();

}

To access the current property value through code:

Properties.Settings.Default[“Username”]

Now, for the additional links I promised. This article offers a more complex and complete solution. Although it’s relatively heavy-weight, it adds support for specific WPF controls, such as saving column positions in a ListView.