WPF Binding My.Settings collection to Combobox items

binding, wpf

Solution

Yes, you can (and should for the most part) declare bindings in XAML, since that's one of the most powerful features in WPF.

In your case, to bind the ComboBox to one of your custom settings you would use the following XAML:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:WpfApplication1.Properties"
    Title="Window1">
    <StackPanel>
        <ComboBox
            ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}" />
    </StackPanel>
</Window>

Notice the following aspects:

- We declared an XML namespace with the prefix 'p' that points to the .NET namespace where the 'Settings' class lives in order to refer to it in XAML

- We used the markup extension '{Binding}' in order to declare a binding in XAML

- We used the markup extension 'Static' in order to indicate that we want to refer to a static ('shared' in VB) class member in XAML

Problem

I'm VERY new to WPF, and still trying to wrap my head around binding in XAML. I'd like to populate a combobox with the values of a string collection in my.settings. I can do it in code like this: Me.ComboBox1.ItemsSource = My.Settings.MyCollectionOfStrings ...and it works. How can I do this in my XAML? is it possible? Thanks

Original source