Delphi 如何使用此CustomSort函数对listview进行排序?
如果customsort函数随变量一起传入,则它似乎会访问冲突Delphi 如何使用此CustomSort函数对listview进行排序?,delphi,callback,Delphi,Callback,如果customsort函数随变量一起传入,则它似乎会访问冲突 public ... col: integer; ... Procedure listviewcol; begin col:=5 ... end; procedure TForm1.sortcol(listview: tlistview); function CustomSortProc(Item1,Item2: TListItem; OptionalParam: integer): integer;stdc
public
...
col: integer;
...
Procedure listviewcol;
begin
col:=5
...
end;
procedure TForm1.sortcol(listview: tlistview);
function CustomSortProc(Item1,Item2: TListItem;
OptionalParam: integer): integer;stdcall;
begin
Result := AnsiCompareText(Item2.subitems.Strings[col], Item1.subitems.Strings[col]);
end;
begin
ListView.CustomSort(@CustomSortProc,0);
end;
这将提示错误。//访问冲突
但是,如果我们将AnsicompareText中的col改为5,则效果良好
procedure TForm1.sortcol(listview: tlistview);
function CustomSortProc(Item1,Item2: TListItem;
OptionalParam: integer): integer;stdcall;
begin
Result := AnsiCompareText(Item2.subitems.Strings[5], Item1.subitems.Strings[5]);// it works.
end;
begin
ListView.CustomSort(@CustomSortProc,0);
end;
如何修复它。
请帮忙。非常感谢。您无法访问回调函数中的
col
,它不是您表单中的方法。将回调嵌套在方法中的技巧是徒劳的。;)如果需要访问表单字段,请使用OptionalParam
在回调中引用表单
begin
ListView.CustomSort(@CustomSortProc, Integer(Self));
[...]
function CustomSortProc(Item1,Item2: TListItem;
OptionalParam: integer): integer; stdcall;
var
Form: TForm1;
begin
Form := TForm1(OptionalParam);
Result := AnsiCompareText(Item2.subitems.Strings[Form.col],
Item1.subitems.Strings[Form.col]);
当然,如果您只需要使用OptionalParam,您可以发送列的值。或者,您可以将“col”设置为全局变量而不是字段,或者使用“Form1”全局变量本身,如果没有注释掉,IDE会将其放在实现部分之前
您还可以使用该事件。将列作为可选参数传递:
function CustomSortProc(Item1,Item2: TListItem; col: integer): integer;stdcall;
begin
Result := AnsiCompareText(Item2.subitems.Strings[col], Item1.subitems.Strings[col]);
end;
begin
ListView.CustomSort(@CustomSortProc, col);
end;
或者使用Sertac答案-他更快:)您能编辑您的问题并使其更具可读性吗?