WPF DataBinding and Application Settings

By Jerome at February 15, 2007 21:47
Filed Under: .NET

Well, yet an other post on WPF and some DataBinding. But this time, this is about DataBinding to application settings that are automatically generated by visual studio. These settings come in handy when you want to save your application settings per user, or have some application wide settings. In my case, I wanted to have my application to remember its size and position, as well as the window state.

WinForms were providing an UI to do this, and I wanted to have all that functionality back. It is not all that "visual" as WinForms can do it, but it works rather well. I guess that Orcas will provide a way to do this visually.

All I had to do to use these settings from XAML was to create a resource to be usable for DataBinding, from a separate file :


File: SettingsRes.xaml



<ResourceDictionary xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

                    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml 

                    xmlns:settings = "clr-namespace:WindowsApplication2.Properties">

  <ResourceDictionary.MergedDictionaries>

    <ResourceDictionary>

      <settings:Settings x:Key="settings" />

    </ResourceDictionary>

  </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

WindowsApplication2 is the default namespace for the application, and since the Settings class is automatically generated, the default namespace is used. This resource will be used application wide and is referenced like this :


<Application.Resources>

  <ResourceDictionary>

    <ResourceDictionary.MergedDictionaries>

      <ResourceDictionary Source = "SettingsRes.xaml"/>

    </ResourceDictionary.MergedDictionaries>

  </ResourceDictionary>

</Application.Resources>

This is handy because resources are separated in multiple files. I also add here references to value converters, when I have to use them everywhere in the application. Value converters, yet an other interesting subject. Maybe in an other post :)

Now, about binding the data. We want to bind the Width, Height and WindowState of the default Window to some settings in the ApplicationSettings.

Here's what to do :


<Window x:Class="WindowsApplication2.Window1"

        xmlns = http://schemas.microsoft.com/winfx/2006/xaml/presentation

        xmlns:x = http://schemas.microsoft.com/winfx/2006/xaml

        Height = "{Binding Source={StaticResource settings}, Path=Default.MainWidth, Mode=TwoWay}"

        Width = "{Binding Source={StaticResource settings}, Path=Default.MainHeight, Mode=TwoWay}"

        WindowState = "{Binding Source={StaticResource settings}, Path=Default.MainState, Mode=TwoWay}">

We create three bindings, each for an attribute, and set the source to the "settings" resource. The interesting part here is that the even thought the property we use is static, Settings.Default here, the Binding engine does seem to support it.

Setting the binding path to Default.MainWidth binds to the appropriate property. The last parameter instructs the binding to set the value of the property when the binding destination value changes, which can be the actual window height, for instance. The type of the property does not need to match the destination exact type, and since the type of the WindowState property is not known by VS2005 settings designer by default, setting the type to string seems to be enough.

Simple and easy. Now my application remembers where it was !

The sample here is a bit more complex, since it includes code to actually save the settings. But this is nothing really complex.

Man ! I like WPF... !

Comments

3/22/2007 4:09:32 PM #

nice sample! I'll try and use this on UniveRSS project! (https://www.microsoft.com/emea/msdn/thepanel/). I tried to use x:Static first to access application settings but it didn't work and your way to go is anyways better because it allows for TwoWay binding! thanx!

kalle vänskä

3/25/2007 3:00:32 AM #

Glad it has helped you Smile I though that some people would be interesed in all this.

I've worked a bit on that one afterward on using converters to bind an array to listbox for instance. This is fun too... Smile

Jay

5/27/2007 8:35:24 PM #

Thank for you a VERY good explaination and simple project to fully understand this concept.

You made my day!

Karl

Karl

5/15/2008 10:47:31 AM #

Pingback from projectfiles.wordpress.com

WPF Certification Study Guide « Project Files

projectfiles.wordpress.com

11/19/2008 2:31:26 AM #

Just an idea... this syntax for binding to settings is quite awkward, so I suggest using this little class instead :

    public class SettingBindingExtension : Binding
    {
        public SettingBindingExtension()
        {
            Initialize();
        }

        public SettingBindingExtension(string path)
            :base(path)
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Source = Properties.Settings.Default;
            this.Mode = BindingMode.TwoWay;
        }
    }


You can then use it like this :

[quote]
<Window x:Class="WindowsApplication2.Window1"
        xmlns="schemas.microsoft.com/.../presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WindowsApplication2"
        Height="{my:SettingBinding Height}"
        Width="{my:SettingBinding Width}"
        WindowState="{my:SettingBinding WindowState}">
[quote]

tom103 France

11/28/2008 4:52:11 AM #

This solution based on resource creates a new instance of the Settings class in addition to Settings.Default. Therefore you have two different settings in your application.

Instead you could use {Binding Source={x:Static settings:Settings.Default}}.

Then Settings.Default.Save() at application exit is enough.

Marko Kohtala Finland

12/14/2008 6:09:53 PM #

Pingback from betsygeorge.com

Saving Window State in WPF  : Inveigled By Design

betsygeorge.com

3/4/2009 9:58:38 AM #

I ended up here looking for something similar.
I want a form that I can pop up from all my .net apps that basically reproduces that settings form visual studio has built into the project properties.
I imagine a WPF grid bound to that settings/properties collection should do the trick, but, I haven’t worked it out just yet.

Alden Snow United States

11/2/2009 7:44:38 AM #

Excellent article thank you sir!

Josh Nall United States

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading




About me

My name is Jerome Laban, I am a Software developer and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Bluetooth Remote Control Software for Windows Mobile.