CASE 1 – You don’t have a data-source:
You can just populate the ComboBox with static values as follows –
- from XAML:
<ComboBox Height="23" Name="comboBox1" Width="120">
<ComboBoxItem Content="Alice"/>
<ComboBoxItem Content="Bob"/>
<ComboBoxItem Content="Charlie"/>
</ComboBox>
- from CodeBehind – 1:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("Alice");
comboBox1.Items.Add("Bob");
comboBox1.Items.Add("Charlie");
}
- from CodeBehind – 2:
// 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 –
- bind the
ItemsSourceproperty inXAMLto the data-source like –
<!-- MyDataSource is an IEnumerable type property in ViewModel -->
<ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" />
- assign data-source to the
ItemsSourceproperty 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
- You should use an
ObservableCollection<T>as the data-source - You should bind the
ItemsSourceproperty inXAMLto the data-source (as shown above) - You can assign data-source to the
ItemsSourceproperty 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>.