【问题标题】:WPF ListBox - how to get multiple selected items in original order, not order of selectionWPF ListBox - 如何以原始顺序而不是选择顺序获取多个选定项目
【发布时间】:2014-03-31 11:05:37
【问题描述】:

我有一个带有 SelectionMode="Extended" 的绑定 WPF 列表框。当我选择多个项目时,使用 Ctrl 键,listBox.SelectedItems 按它们被选中的顺序返回这些项目。我需要它们以原始顺序。这些项目不包含确定这一点的方法。

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

或者有没有更简单的方法?

【问题讨论】:

  • 你如何绑定你的列表框 - 你使用 itemssource 吗?
  • 根据您的项目来源的属性,您可以再次重新排序选择。

标签: wpf listbox wpf-4.0


【解决方案1】:

您可以使用 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]);

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 2012-09-05
    • 1970-01-01
    • 2011-05-01
    • 2023-03-23
    • 2022-11-23
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多