views:

204

answers:

2

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.

+4  A: 

What does e.AddedItems contain? According to MSDN, it should:

Gets a list that contains the items that were selected.

You could also try:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = (sender as ComboBox).SelectedItem.Text;
}
SwDevMan81
interesting ... it has the new value. And RemovedItems has the old. That event name is a bit if a misnomer, at least IMHO. When I see SelectionChanged, I expect the state of the object to, well, have changed. I can see how this gives us slightly more information though.
Matt
Yeah, I think its because the change has occurred, but has not be committed? Thats just a guess. You might be able to get the text of the selected item, see my edit.
SwDevMan81
Both work, thanks!!
Matt
Great, no problem.
SwDevMan81
A: 

The second option didn't work for me because the .Text element was out of scope (C# 4.0 VS2008). This was my solution...

string test = null;
            foreach (ComboBoxItem item in e.AddedItems)
            {
                test = item.Content.ToString();
                break;
            }
Josh