Add items to comboBox in WPF

CASE 1 – You don’t have a data-source:

You can just populate the ComboBox with static values as follows –

  1. from XAML:
<ComboBox Height="23" Name="comboBox1" Width="120">
    <ComboBoxItem Content="Alice"/>
    <ComboBoxItem Content="Bob"/>
    <ComboBoxItem Content="Charlie"/>
</ComboBox>
  1. from CodeBehind – 1:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Add("Alice");
    comboBox1.Items.Add("Bob");
    comboBox1.Items.Add("Charlie");
}
  1. 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 –

  1. bind the 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}" />
  1. assign data-source to the 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

  1. You should use an ObservableCollection<T> as the data-source
  2. You should bind the ItemsSource property in XAML to the data-source (as shown above)
  3. You can assign data-source to the 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>.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)