ComboBox- SelectionChanged事件具有旧值,而不是新值 [英] ComboBox- SelectionChanged event has old value, not new value

查看:89
本文介绍了ComboBox- SelectionChanged事件具有旧值,而不是新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#、. NET 4.0,VS2010。

C#, .NET 4.0, VS2010.

WPF的新功能。我的MainWindow上有一个ComboBox。我迷上了所述组合框的SelectionChanged事件。但是,如果我在事件处理程序中检查组合框的值,则它具有旧值。这听起来更像是 SelectionChanging事件,而不是SelectionChanged事件。

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.

选择实际发生后,如何获得ComboBox的新值?

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

当前:

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

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

注意,如果我使用在事件参数,例如e.OriginalSource。

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

推荐答案

根据MSDN, e.AddedItems

According to MSDN, e.AddedItems:


获取包含所选项目的列表。

Gets a list that contains the items that were selected.

因此您可以使用:

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

您也可以使用 SelectedItem 如果您将字符串值用于发件人物品 c>:

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;
}

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

因为这两个 Content SelectedItem 是对象,更安全的方法是使用 .ToString()而不是作为字符串

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

这篇关于ComboBox- SelectionChanged事件具有旧值,而不是新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆