WPF ListBox - how to get multiple selected items in original order, not order of selection

StackOverflow https://stackoverflow.com/questions/22759985

  •  24-06-2023
  •  | 
  •  

سؤال

I have a bound WPF ListBox with SelectionMode="Extended". When I select more than one item, using the Ctrl key, listBox.SelectedItems returns the items in the order in which they were selected. I need them in the original order. The items don't contain a way to determine that.

Do I need to wrap the items in another class which has an IsSelected property and somehow set that from the ListBox, and then iterate through the whole ItemsSource collection?

Or is there a simpler way?

هل كانت مفيدة؟

المحلول

You can use LINQ to re-apply the original order. It can be done in two steps 1. project your ListBox's items to Dictionary using Select (there's an overload which'll give you the index) 2. Match your selected items against indexed collection and then sort them by the index.

here's some backing code:

var items = new[] { "A", "B", "C", "D" }; // your original items source
var selectedItems = new[] { "D", "C" }; // selection in any order

var indexedItems = items.Select((item, index) => new KeyValuePair<int, string>(index, item)); // indexed items
selectedItems = selectedItems.OrderBy(t => indexedItems.Single(t2 => t2.Value == t).Key).ToArray(); // selected items in the right order

MessageBox.Show(selectedItems[0]);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top