views:

348

answers:

2

In WPF, Can I use binding with values defined in Settings? If this is possible, please provide a sample.

+6  A: 

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 property 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?

M. Jahedbozorgan
I have found that this method only works if the settings file is marked as public access modifier. http://shortfastcode.blogspot.com/2009/12/binding-to-settings-file.html
Daniel
+5  A: 

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://tomlev2.wordpress.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/

Thomas Levesque
Nice,...good extension.
Stimul8d