Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding My.Settings collection to Combobox items

Tags:

binding

wpf

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

like image 645
Ben Brandt Avatar asked Oct 15 '08 13:10

Ben Brandt


2 Answers

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
like image 54
Enrico Campidoglio Avatar answered Sep 25 '22 02:09

Enrico Campidoglio


I have a simpler solution for doing that, using a custom markup extension. In your case it could be used like this :

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:WpfApplication1"
    Title="Window1" Height="90" Width="462" Name="Window1">
    <Grid>
        <ComboBox ItemsSource="{my:SettingBinding MyCollectionOfStrings}" />
    </Grid>
</Window>

You can find the C# code for this markup extension on my blog here : http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/

like image 31
Thomas Levesque Avatar answered Sep 25 '22 02:09

Thomas Levesque