如果耳目一新會再次給你相同的名單,並以相同的順序,那就不必發現關於對象的任何東西。只需存儲列表控件的ItemIndex
屬性,該屬性指示當前選定的項目。
如果刷新可能會給你一個不同的列表,那麼你想要的對象可能不在同一個位置,所以只記得ItemIndex
是不夠的。在這種情況下,您需要找到對象的新位置。如何做到這一點取決於列表控件的功能以及它如何公開與每個位置關聯的對象。例如,如果您有一個TListBox
,則Items
屬性爲TStrings
對象,並且您可以檢查Objects
數組的每個值,直到找到所需的對象。存儲對象引用的值,然後搜索該值。類似這樣的:
procedure Refresh;
var
CurrentSelection: TObject;
ObjectPosition: Integer;
i: Integer;
begin
if List.ItemIndex >= 0 then
CurrentSelection := List.Strings.Objects[List.ItemIndex]
else
CurrentSelection = nil;
RefreshList;
ObjectPosition := -1;
if Assigned(CurrentSelection) then begin
for i := 0 to Pred(List.Count) do begin
if List.Strings.Objects[i] = CurrentSelection then begin
ObjectPosition := i;
break;
end;
end;
end;
if ObjectPosition = -1 then
// Object isn't in refreshed list
else
// It is.
end;
最後的可能性是刷新並不實際上保持相同的對象。所有先前的對象都被銷燬,並且生成一個新的對象列表。在這種情況下,您必須記住原始對象的某些識別特徵,以便可以找到代表相同內容的新對象。事情是這樣的:
var
CurrentObject, Person: TPerson;
CurrentName: string;
i, ObjectPosition: Integer;
begin
if List.ItemIndex >= 0 then begin
CurrentObject := List.Strings.Objects[List.ItemIndex] as TPerson;
CurrentName := CurrentObject.Name;
end else
CurrentName = '';
RefreshList;
ObjectPosition := -1;
if CurrentName <> '' then begin
for i := 0 to Pred(List.Count) do begin
Person := List.Strings.Objects[i] as TPerson;
if Person.Name = CurrentName then begin
ObjectPosition := i;
break;
end;
end;
end;
if ObjectPosition = -1 then
// Object isn't in refreshed list
else
// It is.
end;
在所有這些情況下,你應該認識到該對象在列表中的位置是不實際的對象的屬性。相反,它是列表的屬性,這就是爲什麼列表在所有代碼中扮演比對象更重要的角色的原因。實際上並沒有任何「指針信息」可以從對象中獲取,因爲對象通常不知道它甚至不在列表中,所以它肯定不會知道它相對於列表中的所有其他項的位置。
確定對象在列表中的位置後,需要將其滾動到視圖中。對於TListBox
,一個簡單的方法就是設置其屬性TopIndex
:
List.TopIndex := ObjectPosition;
最後,如果你不真正關心當前對象所有,但只是要恢復當前滾動位置,那麼這更容易:
procedure Refresh;
var
CurrentPosition: Integer;
begin
CurrentPosition := List.TopIndex;
RefreshList;
List.TopIndex := CurrentPosition;
end;
你在找'TListItem.Index'嗎?你失去了我的位置:=整數(TObject。「pointerinfo ????」);' – 2011-04-26 12:53:33
什麼是「圖形列表」和「對象」?您嘗試使用哪些課程?你能展示代碼示例嗎? – Andrew 2011-04-26 13:11:36