0

I have a combo box in my WPF project and I would like to have it items defined by a readonly string array in my configuration class. This way I would make it very easy to reconfigure the combo box items.

Is it possible to bind my ItemsSource property to a readonly string[]? How it can be done?

H.B.
  • 166,899
  • 29
  • 327
  • 400
jpnavarini
  • 763
  • 4
  • 13
  • 25

2 Answers2

3

MainWindow :

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <ComboBox ItemsSource="{Binding List, Source={x:Static local:Configuration.Instance}}"></ComboBox>
</StackPanel>

Configuration File :

public class Configuration
{

    // Singleton              
    private static Configuration _instance;
    public static Configuration Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Configuration();

            return _instance;
        }
    }

    public IEnumerable<string> List
    {
        get
        {
            return new List<string>()
            {
                "toto 1",
                "toto 2"
            };
        }
    }

    public Configuration()
    {

    }
}
Jonas
  • 665
  • 7
  • 14
  • Binding to enum : http://stackoverflow.com/questions/878356/wpf-combobox-binding-to-enum-what-did-i-do-wrong – Jonas Mar 16 '12 at 18:20
  • can you do it without the singleton thing, e.g. if List is just a static property of Configuration? – Louis Rhys Sep 10 '13 at 10:03
  • @LouisRhys Maybe try something like that: http://stackoverflow.com/a/3862828/1073409 – Jonas Sep 10 '13 at 18:58
3

Yes, copy/paste/compile the following:

<ComboBox ItemsSource="Is it possible to Bind a ComboBox (WPF) ItemsSource to a read only string[]"/>
denis morozov
  • 6,236
  • 3
  • 30
  • 45