WPF: Adding items to combobox using ObservableCollection

This entry is part 28 of 54 in the series Learn WPF

ObservableCollection is usually used for providing notifications when new items are added, removed or refleshed in a list.

As in the example below, as new countries are added into the list, the XAML UI will be notified of the change and add the new items into the combo box for selection accordingly.

Here we only make use of the Add method to add new items into a combo box list.

MainWindow.xaml
<Window x:Class="ComboBox1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:ComboBox1"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel  Grid.Column="0"
             Grid.Row="6">
        <StackPanel.Resources>
            <src:VacationSpots x:Key="myVacations"/>
        </StackPanel.Resources>
        <ComboBox Name="comboBox1"
            ItemsSource="{StaticResource myVacations}"
            Text="My Cities"
            IsEditable="true"
            IsReadOnly="true"/>

        <TextBlock Text="{Binding ElementName=comboBox1, Path=SelectedItem}"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;

namespace ComboBox1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    class VacationSpots: ObservableCollection<string>
    {
        public VacationSpots()
        {
            Add("Spain");
            Add("France");
            Add("Peru");
            Add("Mexico");
            Add("Italy");
        }
    }
}

The namespace of this class is System.Collections.ObjectModel which I have added as shown in line 3.

observablecollection

Output when a city country is selected.

cbox

 

Series Navigation<< WPF: Combobox binding
WPF: Adding items to listbox >>

Leave a comment

Leave a Reply