Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Sort TListBox by ItemData.Detail?

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:

Here is an image of an example list that would be sorted

like image 769
Scott Hallauer Avatar asked Apr 19 '17 06:04

Scott Hallauer


1 Answers

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.

like image 145
David Heffernan Avatar answered Sep 30 '22 14:09

David Heffernan