【问题标题】:How to maintain order in SelectedItems of DataGrid?如何维护 DataGrid 的 SelectedItems 中的顺序?
【发布时间】:2013-11-02 08:02:18
【问题描述】:

所以我使用的是 C#/WPF,我有一个 DataGrid。我需要允许用户在DataGrid 中选择多个项目。但是,我注意到SelectedItems 的顺序取决于用户选择它们的方向或顺序。例如,如果它们从下向上拖动,则这些项目基本上与它们在DataGrid 本身中的顺序相反。我需要这些项目在SelectedItems 集合中的顺序与它们在DataGrid 中的顺序相同。

这是我正在做的一个示例:

        DataGrid grid = DataGridWorkoutTemplate;

        if (grid.SelectedItems.Count > 1)
        {
            List<IntervalDisplay> source = (List<IntervalDisplay>)grid.ItemsSource;
            List<IntervalDisplay> newSource = new List<IntervalDisplay>(source);

            foreach (IntervalDisplay row in grid.SelectedItems)
            {
                newSource.Add(row);
            }

            grid.ItemsSource = newSource;

如您所见,我要做的就是将SelectedItems 中的项目再次添加到ItemsSource 的末尾(在本例中为列表),但我需要它们始终是以原来的DataGrid 顺序添加。

如果有更好的方法可以做到这一点,或者您知道如何使用原始顺序,请告诉我。似乎SelectedItems 没有来自DataGrid 的任何固有索引,只有项目按选择顺序排列的索引。而且我真的不想为了处理这个索引而修改基类。

谢谢!

【问题讨论】:

  • 这对我来说似乎很奇怪,但为什么不在将所选项目添加到 itemssource 之前使用快速排序(或任何 c# 中现成的排序)对它们进行排序?

标签: c# wpf datagrid selecteditem


【解决方案1】:

对延迟回答表示歉意,但希望它对未来的读者有所帮助。

我刚刚浏览了 DataGrid 中的所有项目,如果它们被选中,则手动添加它们。

  var selectedList = new ObservableCollection<object>();
  foreach (var item in dataGrid.Items)
  {
    if (dataGrid.SelectedItems.Contains(item))
    {
      selectedList.Add(item);
    }
  }

我使用了“包含”功能,因为我并没有很多项目,所以它不是真正的性能影响,但如果你这样做 - 你可以只使用字典,性能将是好多了。

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 2014-08-10
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多