Add comboBox items from code behind. [WPF]

Set the items programmatically:

Code-behind:

    private void PopulateComboBox()
    {
        cBox.ItemsSource = new List<string> { "Item1", "Item2", "Item3"};
    }

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" />

Bind to a collection of items:

    public class DummyClass
    {
        public int Value { get; set; }
        public string DisplayValue { get; set;}
    }

    public ObservableCollection<DummyClass> DummyClassCollection
    {
        get
        {
            return new ObservableCollection<DummyClass>
            {
                new DummyClass{DisplayValue = "Item1", Value = 1},
                new DummyClass{DisplayValue = "Item2", Value = 2},
                new DummyClass{DisplayValue = "Item3", Value = 3},
                new DummyClass{DisplayValue = "Item4", Value = 4},
            };
        }
    }

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" ItemsSource="{Binding DummyClassCollection}" DisplayMemberPath="DisplayValue" />

Tags:

C#

Wpf

Combobox