简体   繁体   中英

How to maintain order in SelectedItems of DataGrid?

So I'm using C#/WPF and I have a DataGrid . I need to allow the user to select multiple items in the DataGrid . However, I've noticed that the order of SelectedItems depends on which direction or order the user selects them. For instance, if they drag from bottom up, then the items are essentially reversed from the order they had in the DataGrid itself. I need these items to be in the SelectedItems collection in the same order they were in the DataGrid .

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.

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. 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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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