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?
Scenario 1 - you don't have a data-source for the items of the ComboBox
You can just populate the ComboBox with static values as follows -
From XAML:
Or, from CodeBehind:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("X");
comboBox1.Items.Add("Y");
comboBox1.Items.Add("Z");
}
Scenario 2.a - 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 the data-source. You need to assign it to the ItemsSource property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable
).
Scenario 2.b - you have a data-source, and the items might get changed
You should use an ObservableCollectionObservableCollection
). Using an ObservableCollection
ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.