Bind to the value defined in the settings

In WPF, can I use binding with the values ​​defined in the settings? If possible, indicate a sample.

+56
wpf binding appsettings
May 10 '09 at 9:55 a.m.
source share
3 answers

First, you need to add your own XML namespace, which will create a namespace in which the parameters are defined:

xmlns:properties="clr-namespace:TestSettings.Properties" 

Then, in your XAML file, call the default settings instance using the following syntax:

 {x:Static properties:Settings.Default} 

So here is the final result code:

 <ListBox x:Name="lb" ItemsSource="{Binding Source={x:Static properties:Settings.Default}, Path=Names}" /> 

Source: WPF - How to bind a control to a property defined in the settings?




Note. As pointed out by @Daniel and @nabulke, do not forget to set the Access Modifier of your settings file to Public and Scope to User

+97
May 10 '09 at 9:57 a.m.
source share

The solution above works, but I find it pretty detailed ... instead, you can use your own markup extension, which can be used as follows:

 <ListBox x:Name="lb" ItemsSource="{my:SettingBinding Names}" /> 

Here is the code for this extension:

 public class SettingBindingExtension : Binding { public SettingBindingExtension() { Initialize(); } public SettingBindingExtension(string path) :base(path) { Initialize(); } private void Initialize() { this.Source = WpfApplication1.Properties.Settings.Default; this.Mode = BindingMode.TwoWay; } } 

More details here: http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/

+24
May 10 '09 at 23:19
source share

@CSharper's answer did not work for my WPF application encoded in VB.NET (not C #, unlike, apparently, 99.999% of other WPF applications), since I got a constant compiler error complaining that Settings could not be found in MyApp.Properties namespace that will not disappear even after recovery.

Which worked for me after searching the Internet multiple times, instead using the local XAML namespace, created by default in the main XAML application window:

 <Window <!-- Snip --> xmlns:local="clr-namespace:MyApp" <!-- Snip --> ><!-- Snip --></Window> 

... and bind to my settings through it, using something like the following (where MyBooleanSetting is the parameter that I defined in my project properties like Boolean and the user area with the default access modifier):

 <CheckBox IsChecked="{Binding Source={x:Static local:MySettings.Default}, Path=MyBooleanSetting, Mode=TwoWay}" Content="This is a bound CheckBox."/> 

To make sure that the settings are really saved, be sure to call

 MySettings.Default.Save() 

... somewhere in your code (for example, in the Me.Closing event for your MainWindow.xaml.vb file).

(Remember this post in Visual Studio for inspiration; see Muhammad Siddiqui's answer.)

+4
Feb 24 '16 at 15:51
source share



All Articles