如何使用此CustomSort函数对listview进行排序? [英] How to use this CustomSort function to sort listview?
问题描述
如果Customsort函数传入一个变量,它似乎将访问违例。
If customsort function is passed in with a variable, it seems it will access violation.
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;
这将提示错误。 //访问违例
This will prompt errors. // access violation
但是如果我们将Ans在AnsicompareText中的col更改为5,那么效果很好。
But if we change col in AnsicompareText to 5, it works well.
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;
如何解决。
请帮助。非常感谢。
How to fix it. Please help. Thanks a lot.
推荐答案
您无法在回调函数中访问 col
,它不是你的形式的方法。你在一个方法中嵌套回调的技巧是徒劳的。 ;)如果您需要访问表单字段,请使用 OptionalParam
在回调中引用您的表单。
You cannot access col
inside the callback function, it is not a method of your form. Your trick of nesting the callback in a method is futile. ;) If you need to access form fields then use the OptionalParam
to be able to refer to your form in the callback.
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]);
当然你可以发送 col
在'OptionalParam'如果这是唯一你需要的。或者,你可以使'col'一个全局变量而不是一个字段,或者使用IDE中刚刚在执行部分前面的'Form1'全局变量,如果它没有注释掉。
Of course you can send the value of col
in 'OptionalParam' if that's the only thing you need. Or, you can make 'col' a global variable instead of a field, or use the 'Form1' global variable itself which the IDE puts just before the implementation section if it's not commented out.
您还可以使用 OnCompare 活动。
这篇关于如何使用此CustomSort函数对listview进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!