简体   繁体   中英

ListBox SelectionChanged event : get the value before it was changed

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

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.UnselectedItem to get the element that was unselected during the change. Any idea ?

The SelectionChangedEventArgs has a property called RemovedItems which contains a list of items that were removed with the new selection. You can replace EventArgs with SelectionChangedEventArgs and access the property of the parameter (Casting would also work, because it is a subclass).

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        List<string> oldItemNames = new List<string>();
        foreach(var item in e.RemovedItems)
        {
            oldItemNames.Add(item.ToString());
        }
    }

An easy way is to have a private int _selectedIndex that stores the value from the SelectedIndex property, like so:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM