wpf ListBox SelectionChanged 事件:获取更改前的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31520976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ListBox SelectionChanged event : get the value before it was changed
提问by Loukoum Mira
I'm working on a C# wpf application in which there is a listbox, and I'd like to get the value of the element that was selected before a change occur
我正在开发一个 C# wpf 应用程序,其中有一个列表框,我想获取在发生更改之前选择的元素的值
I succeeded in getting the new value this way :
我以这种方式成功获得了新值:
<ListBox SelectionChanged="listBox1_SelectedIndexChanged"... />
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
test.add(listBox1.SelectedItem.ToString());
}
But I would need something like listBox1.UnselectedItemto get the element that was unselected during the change. Any idea ?
但是我需要一些类似的东西listBox1.UnselectedItem来获取在更改期间未选择的元素。任何的想法 ?
回答by Krikor Ailanjian
The SelectionChangedEventArgshas a property called RemovedItemswhich contains a list of items that were removed with the new selection. You can replace EventArgswith SelectionChangedEventArgsand access the property of the parameter (Casting would also work, because it is a subclass).
该SelectionChangedEventArgs有一个名为属性RemovedItems包含有新的选择中删除的项目列表。您可以替换EventArgs使用SelectionChangedEventArgs和访问参数的属性(铸造也将工作,因为它是一个子类)。
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<string> oldItemNames = new List<string>();
foreach(var item in e.RemovedItems)
{
oldItemNames.Add(item.ToString());
}
}
回答by Chris Schubert
An easy way is to have a private int _selectedIndexthat stores the value from the SelectedIndex property, like so:
一个简单的方法是让一个private int _selectedIndex存储来自 SelectedIndex 属性的值,如下所示:
private int _selectedIndex;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
test.add(listBox1.SelectedItem.ToString());
// grab the _selectedIndex value before we update it.
var oldValue = _selectedIndex;
_selectedIndex = listBox1.SelectedIndex;
// code utilizing old and new values
// oldValue stores the index from the previous selection
// _selectedIndex has the value from the current selection
}

