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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With