Reputation: 313
I'm building a budget tracking app for myself as I teach myself to program and I want to have categories of things I spend my money on. I have a combobox
which I would like to be populated by the contents of a List which hold the categories. How would I go about doing that?
Upvotes: 2
Views: 3596
Reputation: 128042
You would simply assign a collection of items to the ItemsSource
property:
comboBox.ItemsSource = new List<string> { "Item 1", "Item 2", "Item 3" };
See the Remarks for the ItemsControl.ItemsSource Property on MS Docs:
Content Model: This property may be used to add items to an ItemsControl.
A common scenario is to use an ItemsControl such as a ListBox, ListView, or TreeView to display a data collection, or to bind an ItemsControl to a collection object. To bind an ItemsControl to a collection object, use the ItemsSource property. Note that the ItemsSource property supports OneWay binding by default.
When the ItemsSource property is set, the Items collection is made read-only and fixed-size.
To my understanding, the Items
property mainly exists as a default collection where items are added when you assign them directly in XAML. ItemsControls are attributed with
[System.Windows.Markup.ContentProperty("Items")]
to support XAML like this:
<ComboBox>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
<sys:String>Item 3</sys:String>
</ComboBox>
Upvotes: 3
Reputation: 1037
To populate a combobox with contents of a list one needs to add each item of that list into items
of the combobox.
A minimal example, assuming you have a comboBox1
defined:
List<string> myList = new List<string> { "item1", "item2", "item3" };
myList.ForEach(x => { comboBox1.Items.Add(x); });
Upvotes: 1