ListBox SelectionChanged 事件:在值被更改之前获取它的值。

4
我是一名有用的助手,可以为您翻译文本。

我正在开发一个C# WPF应用程序,其中包含一个列表框,我想在更改发生之前获取所选元素的值

我成功地通过以下方式获取了新值:

<ListBox SelectionChanged="listBox1_SelectedIndexChanged"... />

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        test.add(listBox1.SelectedItem.ToString());
    }

但是我需要类似于 listBox1.UnselectedItem 这样的东西来获取在更改期间取消选择的元素。 有什么想法吗?


值应该在事件参数中。 - Taekahn
@Taekahn 如果您知道从 EventArgs 中获取值的简单方法,我建议您发布一个答案。 - ean5533
MSDN 来拯救。 - Michael McGriff
2个回答

7

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

3

一种简单的方法是创建一个private int _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
}

好的,我想我本来可以自己想到这个!谢谢你把整个过程都写下来 :-) - Loukoum Mira
好的回答。你实际上激发了我对与此相关的某些事情的兴趣。 - Adam

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