简体   繁体   中英

WPF Listbox.selecteditems returns items in the order they were selected

I was debugging a co-workers program and ran across this issue in WPF.

It looks like the listBoxName.SelectedItems returns a list of selected items, in the order a user selects the item from the interface. This is a problem because I need to preserve the actual order the items.

Example:

the listbox is in Extended selectmode and my listbox contains something: runfirst, runsecond, runthird

the user is given an option to select what they want to run based from the listbox. They select runthird then runfirst. This causes runthird to appear at the top of the list and then runfirst. I guess i could sort the list before running a foreach but i was wondering if there is an easier way.

Thanks

What I did was use LINQ to return the selected items in index order. It is in VB.Net syntax, but it should be easy to fix up for C#.

Dim selecteditems = From selecteditem As ListBoxItem In ListBox1.SelectedItems _
                    Select selecteditem _
                    Order By ListBox1.Items.IndexOf(selecteditem)

Yeah I ended up iterating over all the items in the in the listbox and then checked if it was in selecteditems using contains as below

            foreach (<yourobject> item in listForSelection.Items)
            {
                if (listForSelection.SelectedItems.Contains(item))
                {
                     \\code here
                }
            }

Thanks for the help guys

I think you gave the answer in your question.

Most of the time the order of selected items won't matter. Since it does for you, sorting the selected items before processing them seems to be the simplest solution. I can't really think of a simpler one, especially when the sorting should only add 1 line.

You can use the same Comparison<T> or IComparer<T> that was used to sort the original list. If you're binding to SelectedItems , you can use an IValueConverter to do the sorting.

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