2010-11-04 31 views
2

如果通過一個變量傳入的是傳遞函數,它似乎會訪問衝突。如何使用此CustomSort函數對listview進行排序?


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; 

如何解決此問題。 請幫忙。非常感謝。

+3

可以請編輯您的問題,並使其更具可讀性? – 2010-11-04 11:47:15

回答

5

你不能訪問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值如果這是你唯一需要的。或者,你可以使'col'變成一個全局變量而不是一個字段,或者如果沒有被註釋掉,就使用IDE放在實現部分之前的'Form1'全局變量本身。您可以使用OnCompare事件。

2

通關口的OptionalParam:

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答案 - 他快:)

+0

非常感謝。 SERG。 – Dylan 2010-11-04 12:14:01

相關問題