In WPF, Can I use binding with values defined in Settings? If this is possible, please provide a sample.
In WPF, Can I use binding with values defined in Settings? If this is possible, please provide a sample.
First, you need to add a custom XML namespace that will design the namespace where the settings are defined:
xmlns:properties="clr-namespace:TestSettings.Properties"
Then, in your XAML file, access 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, don't forget to set Access Modifier of your settings file to Public and Scope to User
The solution above does work, but I find it quite verbose... you could use a custom markup extension instead, that could be used like this :
<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/
Here's how I bind the UserSettings:
Generate a dependency variable by typing propdp and then tab twice.
public UserSettings userSettings
{
get { return (UserSettings)GetValue(userSettingsProperty); }
set { SetValue(userSettingsProperty, value); }
}
public static readonly DependencyProperty userSettingsProperty =
DependencyProperty.Register("userSettings", typeof(UserSettings), typeof(MainWindow), new PropertyMetadata(UserSettings.Default));
Now, you can bind userSettings by:
Value="{Binding userSettings.SomeUserSettingHere, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
And make sure you save UserSettings when you change them or on Exit by:
UserSettings.Default.Save();