Search code examples
c#wpfcombobox.net-4.0selectionchanged

ComboBox- SelectionChanged event has old value, not new value


C#, .NET 4.0, VS2010.

New to WPF. I have a ComboBox on my MainWindow. I hooked the SelectionChanged event of said combo box. However, if I examine the value of the combo box in the event handler, it has the old value. This sounds more like a "SelectionChanging" event, than a SelectionChanged event.

How do I get the new value of the ComboBox after the selection has actually happend?

Currently:

this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnMyComboBoxChanged);

...
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = this.MyComboBox.Text;
}

Note, I get the same behaviour if I use the object being passed in the event args, e.g. e.OriginalSource.


Solution

  • According to MSDN, e.AddedItems:

    Gets a list that contains the items that were selected.

    So you could use:

    private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
    {
        string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
    }
    

    You could also use SelectedItem if you use string values for the Items from the sender:

    private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
    {
        string text = (sender as ComboBox).SelectedItem as string;
    }
    

    or

    private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
    {
        string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
    }
    

    Since both Content and SelectedItem are objects, a safer approach would be to use .ToString() instead of as string