Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

ListView Sort Elements

Discussion in 'UI Toolkit' started by mrSaig, Jun 11, 2020.

  1. mrSaig

    mrSaig

    Joined:
    Jan 14, 2010
    Posts:
    68
    Hey how do I sort the items for the listview?

    I tried sorting the input array ... but it just stays the same?! Am I misssing something?

    Code (CSharp):
    1. List<TableChance> chances = new List<TableChance>(unsortedChances);        
    2. chances.Sort((x, y) => x.rangeMin.CompareTo(y.rangeMin));        
    3. listView_chances.itemsSource = chances.ToArray();
    4. listView_chances.Refresh();
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    That should have worked. Items in the itemsSource are displayed in order in ListView. Note that you don't need to convert your List to an Array to give it to itemsSource. But I would confirm the sort worked with a debug print before giving it to listiview and then maybe try deleting the ListView element and recreating it to see if that preserves the order. Either way, sounds like a bug.
     
  3. Iam01c

    Iam01c

    Joined:
    Nov 14, 2015
    Posts:
    3
    Same problem in 2022.3.18f1.
    Debugging and printing shows the sorted list, but no change in the actual ListView, tried with both RefreshItems() and Rebuild().

    Edit:
    Sorting the actual reference of itemsSource works, no need to create a new list.
    i.e. like this:
    myListView.itemsSource = mySource;
    ...
    mySource.Sort(...)
    myListView.RefreshItems()
     
    Last edited: Mar 9, 2024