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

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


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


I like the accepted answer, I ran into a special case though. I had my text box set as "read only" so that I can change the value of it only in the code. I couldn't understand why the value wasn't propagated back to the Settings although I had the Mode as "TwoWay".

Then, I found this: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while the Text property has a default value of LostFocus.

Thus, if you have the text box with IsReadOnly="True" property, you have to add a UpdateSourceTrigger=PropertyChanged value to the Binding statement:

<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />