Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox SelectionChanged event : get the value before it was changed

Tags:

c#

wpf

xaml

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 ?

like image 449
Loukoum Mira Avatar asked Jan 08 '23 22:01

Loukoum Mira


1 Answers

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());
        }
    }
like image 69
Krikor Ailanjian Avatar answered Jan 27 '23 18:01

Krikor Ailanjian