ComboBox- SelectionChanged 事件具有旧值,而不是新值 [英] ComboBox- SelectionChanged event has old value, not new value
问题描述
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;
}
如果您对来自 sender
的 Items
使用 string
值,您也可以使用 SelectedItem
:>
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屋!