WPF ListBox - 如何按原始顺序获取多个选定项目,而不是选择顺序

时间:2014-03-31 11:05:38

标签: wpf listbox wpf-4.0

我有一个绑定的WPF ListBox,SelectionMode =“Extended”。当我选择多个项目时,使用Ctrl键,listBox.SelectedItems将按照选择顺序返回项目。我按原来的顺序需要它们。这些项目不包含确定该方法的方法。

我是否需要将项目包装在另一个具有IsSelected属性的类中,并以某种方式从ListBox中设置它,然后遍历整个ItemsSource集合?

或者有更简单的方法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用LINQ重新应用原始订单。它可以分两步完成 1.使用Select将ListBox的项目投影到Dictionary(有一个重载会给你索引) 2.将所选项目与索引集合进行匹配,然后按索引对它们进行排序。

这里有一些支持代码:

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]);
相关问题