Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
Kris Erickson Avatar asked Sep 30 '08 19:09

Kris Erickson


People also ask

What is oneway binding WPF?

In One Way binding, source control updates the target control, which means if you change the value of the source control, it will update the value of the target control. So, in our example, if we change the value of the slider control, it will update the textbox value, as shown below.

What is two way binding WPF?

In two way we can change data in sources control and target control. Target to source and source to target means if we change source control value then it will automatically change target control value. And vice-a versa for source control. That's why it's called two-way data binding.


2 Answers

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);  } 
like image 160
Sacha Bruttin Avatar answered Sep 21 '22 03:09

Sacha Bruttin


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

like image 41
TknoSpz Avatar answered Sep 22 '22 03:09

TknoSpz