2017-08-20 62 views
0

我有一个组合框和一个按钮。当我点击按钮时,应该更改选定的值,然后在更改项目时触发代码。不幸的是,在我设置组合框的选定值之前,选择改变了事件触发。使用选定值(C#WPF)时选择更改之前组合框选择更改事件触发

我的组合框的初始化代码:

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")); 

我的按钮的代码:

ListCB.SelectedValue = 3; 

我的选择更改事件:

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

什么情况是,如果比如我选1从组合框中单击按钮,它会显示现在的值是:一个而不是三个。

我使用了错误的事件吗?还是我用错误的方式来改变选定的值?

+0

ListCB.SelectedIndex按预期工作,但不幸的是,内容是挥发性它不是可行的我的使用。 –

回答

0

使用SelectionChangedEventArgs得到新选定的项目

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

谢谢,这个工作,它现在说正确的价值。不过,我有一个问题,只有在消息框完成后,组合框项目更新的原因是什么? –

+0

@KlausBean对于它的工作原理有一个很好的解释https://stackoverflow.com/a/31574510/2189031。简而言之,在将'sender'转换为'ComboBox'之后,您需要使用'SelectedItem'而不是'SelectedValue'。 – Mitya

+0

对不起,我刚刚回来,谢谢你的链接。 –

相关问题