WPF ComboBox SelectionChanged


The user of your WPF has just made a selection in the ComboBox on your GUI. Which one did they choose?

I found that code is not so obvious. In fact, I had to go to a book and StackOverflow and combine the two suggestions together to get the following solution that answers the question: “What the the user pick?”.

<Window x:Class="ComboBoxSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ComboBoxSimple"
        mc:Ignorable="d"
        WindowStartupLocation="CenterOwner"
        Title="ComboBoxSimple" Height="150" Width="300">
    <StackPanel Margin="10">
        <ComboBox Name="cboBox" SelectionChanged="CboBox_SelectionChanged">
            <ComboBoxItem>ComboBox Item #1</ComboBoxItem>
            <ComboBoxItem IsSelected="True">ComboBox Item #2</ComboBoxItem>
            <ComboBoxItem>ComboBox Item #3</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</Window>

Below is the code behind.

using System.Windows;
using System.Windows.Controls;
namespace ComboBoxSimple
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void CboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                // BOTH of the following sets of code get the user's selection
                string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
                if (text != null)
                {
                    MessageBox.Show(text, "text");
                }
                string text2 = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
                if (text2 != null)
                {
                    MessageBox.Show(text2, "text2");
                }
            }            
        }
    }
}