Delphi Sort TListBox by ItemData.Detail?

I have a TListBox containing a list of locations (each with a name and distance from your current location). I would like to give users the ability to sort the list by location name (for example, in alphabetical order) or by distance from their current location. The location name is saved as the ItemData.Text value of the item, and the distance from the current location is saved as the ItemData.Detail value. The problem is that the normal TListBox sorting method does not use the ItemData.Detail property when sorting (just the ItemData.Text property). Can I add my own sorting method to a TListBox that is sorted according to the ItemData.Detail value for each item?

I tried the following, but it does not work:

procedure TFrmSelect.btnSortLocationClick(Sender: TObject); var Compare: TFMXObjectSortCompare; begin btnSortLocation.Enabled := False; btnSortAlpha.Enabled := True; Compare := function(item1, item2: TFmxObject): Integer begin Result := TListBoxItem(item1).ItemData.Detail.CompareTo(TListBoxItem(item2).ItemData.Detail); end; self.ListBox.Sort(Compare); self.ListBox.Sorted := False; self.ListBox.Sorted := True; end; 

Here is an image of a list of examples to be sorted:

Here is an image of a list of examples to be sorted

+5
source share
1 answer

The Sort call sorts using the comparison function. The Sorted property is used to maintain the list in the default order.

To order a list using the comparison function, simply remove the code that sets the Sorted property.

+5
source

Source: https://habr.com/ru/post/1266894/


All Articles