简体   繁体   中英

Combo Box Selection Changed Event fires before Selection Changes when using Selected Value (C# WPF)

I have a combo box and a button. When I click the button, it's supposed to change the selected value and then fire the code when the item was changed. Unfortunately, the selection changed event fires before I set the selected value of the combo box.

My Combo Box's code on initialize:

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(1, "One"));

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(2, "Two"));

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(3, "Three"));

My Button's code:

ListCB.SelectedValue = 3;

My Selection Changed Event:

private void ListCB_Change(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("Value is now: " + ListCB.SelectedValue);
}

What happens is if for example I select 1 from the combo box and click the button, it will say Value now is: One instead of Three.

Am I using the wrong event? Or am I using a wrong way to change the selected value?

Use SelectionChangedEventArgs to get newly selected item

private void ListCB_Change(object sender, SelectionChangedEventArgs e)
{
    var item = (KeyValuePair<int, string>)e.AddedItems[0];
    MessageBox.Show("Value is now: " + item.Key);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM