Best way to bind WPF properties to ApplicationSettings in C#?

What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to this question, how (and is it possible to) do you do the same thing in WPF?


You can directly bind to the static object created by Visual Studio.

In your windows declaration add:

xmlns:p="clr-namespace:UserSettings.Properties"

where UserSettings is the application namespace.

Then you can add a binding to the correct setting:

<TextBlock Height="{Binding Source={x:Static p:Settings.Default}, 
           Path=Height, Mode=TwoWay}" ....... />

Now you can save the settings, per example when you close your application:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    Properties.Settings.Default.Save();
    base.OnClosing(e); 
}

In case you are a VB.Net developer attempting this, the answer is a smidge different.

xmlns:p="clr-namespace:ThisApplication"

Notice the .Properties isn't there.


In your binding it's MySettings.Default, instead of Settings.Default - since the app.config stores it differently.

<TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...

After a bit of pulling out my hair, I discovered this. Hope it helps