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

I debugged an employee program and ran into this problem in WPF.

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

Example:

the list is in Extended selectmode and my list contains something: runfirst, runningecond, runthird

the user is given the opportunity to choose from which they will be launched from the list. They choose runthird and then runfirst. This causes runthird to appear at the top of the list, and then start over. I think I could sort the list before starting foreach, but I was wondering if there is an easier way.

thanks

+4
source share
3 answers

Yes, I ended up looping through all the items in the list and then checking to see if it was in the selecteditems file as shown below

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

Thanks for helping the guys

+3
source

I used LINQ to return the selected items in index order. This is the syntax of VB.Net, but it needs to be easily fixed for C #.

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

I think you answered in your question.

In most cases, the order of the selected items does not matter. Since this is for you, sorting selected items before processing them seems like the easiest solution. I can't think of a simpler one, especially if sorting should only add 1 row.

You can use the same Comparison<T> or IComparer<T> that were used to sort the source list. If you are attached to SelectedItems , you can use IValueConverter to sort.

+1
source

Source: https://habr.com/ru/post/1302255/


All Articles