WPF组合框 - SelectionChanged事件已经老了价值,而不是新的组合、而不是、事件、价值

2023-09-07 11:15:23 作者:「﹎荫涧见┐

C#,.NET 4.0,VS2010。

C#, .NET 4.0, VS2010.

新的WPF。我有我的主窗口组合框。我迷上表示组合框中的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的新的价值选择之后,实际上已经happend?

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 如果你使用字符串值的产品

You could also use SelectedItem if you use string values for the Items:

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

由于两个内容的SelectedItem 是对象,一个更安全的方法是使用的ToString()而不是为字符串

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

 
精彩推荐
图片推荐