WPF: XAML ComboBox

A ComboBox is just like a drop down list in HTML.

Here we use some XAML tags to work out a ComboBox.  We have made the ComboBox to be editable, so you can actually type in the box to make a selection.

MainWindow.xaml
<Window x:Class="ComboBox2.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">
    <StackPanel Margin="20,20,20,20">
        <TextBox Width="200" Height="30" HorizontalAlignment="left">Where would you like to go today?</TextBox>
        <ComboBox Name="cb" SelectionChanged="DisplayOutput" Text="My Cities" IsEditable="true">
            <ComboBoxItem>Spain</ComboBoxItem>
            <ComboBoxItem>France</ComboBoxItem>
            <ComboBoxItem>Peru</ComboBoxItem>
            <ComboBoxItem>Mexico</ComboBoxItem>
            <ComboBoxItem>Italy</ComboBoxItem>
        </ComboBox>
        <TextBlock Name="tb" Width="200" Height="30" HorizontalAlignment="Center" Margin="10,100,50,50">You selected</TextBlock>
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

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

        void DisplayOutput(object sender, SelectionChangedEventArgs args)
        {
            ComboBoxItem cb = ((sender as ComboBox).SelectedItem as ComboBoxItem);
            tb.Text = "You selected " + cb.Content.ToString() + ".";
        }
    }
}

xamlcombobox

 

Series Navigation<< WPF: Simple combobox data binding
WPF: Combobox binding >>