ComboBox
This WPF control provides a drop-down list of strings. The user clicks on the box, and the items appear. We use properties like ItemsSource
and IsEditable
.
First, we create a new WPF project and drag a ComboBox
to the Window. This causes Visual Studio to insert the ComboBox
element in the XAML file.
Loaded
exampleTo use the ComboBox
, we can add a Loaded
event handler for it. This is a good place to initialize. We specify the Loaded
and SelectionChanged
events.
Loaded
" and Visual Studio will create the C# event handler.ComboBox_Loaded
event handler to specify the items in the control at runtime.List
of strings to the ItemsSource
.SelectionIndex
property to 0. This sets the first element in the List
in the ComboBox
.<Window x:Class="WpfApplication9.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ComboBox HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="120" Loaded="ComboBox_Loaded" SelectionChanged="ComboBox_SelectionChanged"/> </Grid> </Window>using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace WpfApplication9 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ComboBox_Loaded(object sender, RoutedEventArgs e) { // ... A List. List<string> data = new List<string>(); data.Add("Book"); data.Add("Computer"); data.Add("Chair"); data.Add("Mug"); // ... Get the ComboBox reference. var comboBox = sender as ComboBox; // ... Assign the ItemsSource to the List. comboBox.ItemsSource = data; // ... Make the first item selected. comboBox.SelectedIndex = 0; } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // ... Get the ComboBox. var comboBox = sender as ComboBox; // ... Set SelectedItem as Window Title. string value = comboBox.SelectedItem as string; this.Title = "Selected: " + value; } } }
SelectionChanged
We also use the ComboBox_SelectionChanged
event handler. We display the currently selected item in the ComboBox
as part of the Window Title.
ItemsSource
The ItemsSource
is a property on the ComboBox
. It can be assigned to any reference object that implements the IEnumerable
interface
.
IEnumerable
includes arrays and Lists. We can set all the items in a single assignment.List
or array) as the items.A ComboBox
presents the user with a choice. We populate the ComboBox
with the ItemsSource
property. And in event handlers (SelectionChanged
) we act on user input.