I have a TListBox containing a list of locations (each with a name and a distance from your current location). I would like to give users the option to sort the list by either the location name (i.e. alphabetically) or by the distance from their current location. The location name is stored as the item's ItemData.Text value and the distance from the current location is stored as the ItemData.Detail value. The problem is that the regular TListBox sort method does not use the ItemData.Detail property when sorting (just the ItemData.Text property). Is it possible to add a custom sort method to the TListBox which sorts according to the ItemData.Detail value of each item?
I have 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 an example list that would be sorted:
The call to Sort
performs the sort using your compare function. The Sorted
property is used to maintain the list in an order determined by the default compare.
In order to order the list using your compare function simply remove the code that sets the Sorted
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With