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


Question

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?

1
47
5/23/2017 11:54:43 AM

Accepted Answer

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); 
}
102
5/2/2013 2:13:46 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon