When I have added a comboBox to the WPF window, how do I add items to the comboBox? Int the XAML code for the design or in NameOfWindow.xaml.cs file?
On button click event handler, we add the content of TextBox to the ComboBox by calling ComboBox. Items. Add method. Now if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the ComboBox.
To add items to a ComboBox, select the ComboBox control and go to the properties window for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.
A combobox is a selection control that combines a non-editable textbox and a drop-down listbox that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item.
Data binding the ComboBox Each item, as defined by the ItemTemplate, consists of a StackPanel with a Rectangle and a TextBlock, each bound to the color value.
CASE 1 - You don't have a data-source:
You can just populate the ComboBox
with static values as follows -
<ComboBox Height="23" Name="comboBox1" Width="120"> <ComboBoxItem Content="Alice"/> <ComboBoxItem Content="Bob"/> <ComboBoxItem Content="Charlie"/> </ComboBox>
private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.Items.Add("Alice"); comboBox1.Items.Add("Bob"); comboBox1.Items.Add("Charlie"); }
// insert item at specified index of populated ComboBox private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.Items.Insert(2, "Alice"); comboBox1.Items.Insert(5, "Bob"); comboBox1.Items.Insert(8, "Charlie"); }
CASE 2 - You have a data-source, and the items never get changed:
You can use the data-source to populate the ComboBox
. Any IEnumerable
type can be used as a data-source. You can -
ItemsSource
property in XAML
to the data-source like -<!-- MyDataSource is an IEnumerable type property in ViewModel --> <ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" />
ItemsSource
property in the code-behind, like -private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.ItemsSource = new List<string> { "Alice", "Bob", "Charlie" }; }
CASE 3 - You have a data-source, and the items might get changed
ObservableCollection<T>
as the data-sourceItemsSource
property in XAML
to the data-source (as shown above)ItemsSource
property in the code-behind (as shown above)Using an ObservableCollection<T>
ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI. It's up to you how you populate the ObservableCollection<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With