简体   繁体   English

如何维护DataGrid的SelectedItems中的顺序?

[英]How to maintain order in SelectedItems of DataGrid?

So I'm using C#/WPF and I have a DataGrid . 所以我正在使用C#/ WPF并且有一个DataGrid I need to allow the user to select multiple items in the DataGrid . 我需要允许用户在DataGrid选择多个项目。 However, I've noticed that the order of SelectedItems depends on which direction or order the user selects them. 但是,我注意到SelectedItems的顺序取决于用户选择它们的方向或顺序。 For instance, if they drag from bottom up, then the items are essentially reversed from the order they had in the DataGrid itself. 例如,如果它们从下往上拖动,则这些项目实际上与它们在DataGrid本身中的顺序相反。 I need these items to be in the SelectedItems collection in the same order they were in the DataGrid . 我需要这些项目以与DataGrid相同的顺序位于SelectedItems集合中。

Here's a sample of what I'm doing: 这是我在做什么的一个示例:

        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;

As you can see, all I'm trying to do is take the items in SelectedItems and add them again to the end of the ItemsSource (a List in this case), but I need them to always be added in in their original DataGrid order. 如您所见,我想要做的就是将项目放入SelectedItems然后将它们再次添加到ItemsSource的末尾(在本例中为List),但我需要始终按其原始DataGrid顺序添加它们。

If there's a better way to do this, or you know how to make it use the original order, let me know. 如果有更好的方法可以执行此操作,或者您知道如何使它使用原始订单,请告诉我。 It seems like SelectedItems doesn't have any inherent index from the DataGrid , just the index of the items in the order they were selected. 似乎SelectedItems没有来自DataGrid任何固有索引,仅是按项目选择顺序的项目索引。 And I don't really want to modify the base class just to handle this indexing. 而且我真的不想仅仅为了处理此索引而修改基类。

Thanks! 谢谢!

Apologies for the delayed answer, but hopefully it will help for future readers. 对于延迟回答,我们深表歉意,但希望对以后的读者有所帮助。

I just went through all the items in the DataGrid and added them manually if they're selected. 我只是浏览了DataGrid中的所有项目,并在选中它们后手动添加了它们。

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

I've used the "Contains" function because I don't really have a lot of items, so it isn't a real performance hit, but if you do - you can just use a dictionary and the performance will be much better. 我使用了“包含”功能,因为我实际上没有很多东西,因此它并不是真正的性能问题,但是如果您这样做了,您可以使用词典,这样性能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM