ComboBox - SelectionChanged事件具有旧值而不是新值

108

C#,.NET 4.0,VS2010。

我是WPF的新手。 我在我的MainWindow上有一个ComboBox。 我已经连接了该组合框的SelectionChanged事件。 但是,如果我在事件处理程序中检查组合框的值,则会显示旧值。 这更像是一个“SelectionChanging”事件,而不是SelectionChanged事件。

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

当前:

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

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

注意,如果我使用事件参数中传递的对象(例如e.OriginalSource),我会获得相同的行为。


2
我刚刚遇到了同样的问题 - 谢谢!这实际上是一个错误吗?它一开始应该被命名为*SelectionChanging*吗? - Jan
检查ComboBox.OnSelectionChanged方法的源代码,显示它发布事件,然后处理所选项目。在一个相关的问题中,我使用反射来强制它从我的SelectionChanged事件处理程序中处理所选项目。 - Tony Pulokas
19个回答

0

简洁易懂 - TextChanged

private void ComboBox1_TextChanged(object sender, EventArgs e)
    {
        MessageBox.Show(ComboBox1.Text);
    }

0

以下是我用于获取ComboBox当前选择的方法(c# / .net6):

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    string? text = ((ComboBoxItem)(sender as ComboBox).SelectedItem).Content as string;
    
    if(text != null){
        ...
    }
}

0

这很奇怪,SelectedItem 保存了最新的数据,而 SelectedValue 却没有。对我来说听起来像是个 bug。如果你的 ComboBox 中的项不是 ComboBoxItems 的对象,则需要像这样的东西:(我的 ComboBox 包含 KeyValuePair

var selectedItem = (KeyValuePair<string, string>?)(sender as ComboBox).SelectedItem;
if (!selectedItem.HasValue)
    return;

string selectedValue = selectedItem.Value.Value;  // first .Value gets ref to KVPair

ComboBox.SelectedItem 可以为 null,而 Visual Studio 始终告诉我 KeyValuePair 不能为 null。这就是为什么我将 SelectedItem 强制转换为可空的 KeyValuePair<string, string>?。然后我检查 selectedItem 是否具有除 null 以外的值。这种方法适用于您选择的任何类型。


0
在 Combobox 控件的 SelectionChanged 事件中,您可以检查 SelectedIndex、SelectedValue 或 SelectedItem 属性。

0

我需要在VB.NET中解决这个问题。以下是我得到的似乎可以工作的代码:

Private Sub ComboBox1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox_AllSites.SelectionChanged
   Dim cr As System.Windows.Controls.ComboBoxItem = ComboBox1.SelectedValue
   Dim currentText = cr.Content
   MessageBox.Show(currentText)
End Sub

0

不要无缘无故地把事情复杂化。使用SelectedValue属性,您可以轻松地获取所选ComboBox的值,如下所示:YourComboBoxName.SelectedValue.ToString()。

在幕后,SelectedValue属性被定义为:SelectedValue{get; set;},这意味着您可以使用它来获取或设置ComboBox的值。

使用SelectedItem不是获取ComboBox值的有效方法,因为它需要很多分支。


0

从组合框的SelectionChanged事件中,您可以按以下方式获取所选项目的文本:

        private void myComboBox_SelectionChanged (object sender, SelectionChangedEventArgs e)
        {
        ComboBoxItem comboBoxItem = (ComboBoxItem) e.AddedItems[0];
        string selectedItemText = comboBoxItem.Content.ToString();
        }

-3

这应该对您有用...

int myInt= ((data)(((object[])(e.AddedItems))[0])).kid;

2
你能解释一下这个回答如何回答了问题吗? - Nathan Tuggy

-3
我通过使用DropDownClosed事件来解决这个问题,因为它在值更改后略微延迟被触发。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接