我需要啓用或禁用某個按鈕,具體取決於列表中是否至少選擇了一行。TListView SelCount報告虛擬列表中的項目數量錯誤
下面是重現此問題的代碼。該列表使用OnData事件填充,並允許選擇多行。
我認爲我可以使用OnSelectItem來檢測用戶何時更改選擇,然後使用TListView SelCount函數來檢測選定行的數量。
問題是,當用戶選擇多行時,SelCount返回0。如果手動填充列表(即不通過OnData事件),這可以正常工作。
任何想法?
感謝
更新:使用OnChange事件,而不是似乎這樣的伎倆。如果選擇多行(從SelectItem事件中),爲什麼SelCount返回0,仍然會很有趣。
另一個更新:我發佈一個測試項目:https://dl.dropboxusercontent.com/u/35370420/TestListView2.zip以及截圖:
重現此問題運行應用程序,選擇項目1,然後按Shift +單擊項目2。該按鈕被禁用。我的意圖是隻要列表中至少有一個項目被選中,就可以動態地啓用該按鈕。如果沒有選定的項目,該按鈕被禁用。
PAS文件:
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls;
type
TForm3 = class(TForm)
ListView1: TListView;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure ListView1Data(Sender: TObject; Item: TListItem);
procedure ListView1SelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
procedure TForm3.FormCreate(Sender: TObject);
begin
ListView1.Items.Count := 5;
end;
procedure TForm3.ListView1Data(Sender: TObject; Item: TListItem);
begin
Item.Caption := String.Format('Item%d', [Item.Index]);
end;
procedure TForm3.ListView1SelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
begin
Button1.Enabled := ListView1.SelCount > 0;
OutputDebugString(pchar(String.Format('SelCount = %d', [ListView1.SelCount])));
end;
end.
形式:
object Form3: TForm3
Left = 0
Top = 0
Caption = 'Form3'
ClientHeight = 600
ClientWidth = 952
Color = clBtnFace
DoubleBuffered = True
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object ListView1: TListView
Left = 168
Top = 160
Width = 250
Height = 150
Columns = <
item
AutoSize = True
Caption = 'Test'
end>
HideSelection = False
MultiSelect = True
OwnerData = True
TabOrder = 0
ViewStyle = vsReport
OnData = ListView1Data
OnSelectItem = ListView1SelectItem
end
object Button1: TButton
Left = 168
Top = 120
Width = 75
Height = 25
Caption = 'Some Action'
Enabled = False
TabOrder = 1
end
end
fyi - 我無法重現Delphi 7中的錯誤。 –
-1在XE5中,問題中的代碼按預期工作,而不像您所描述的那樣。 –
@DavidHeffernan:你運行過什麼操作系統?我正在使用最新更新的Windows 7 64位和XE5。您可以從這裏下載該項目:https://dl.dropboxusercontent.com/u/35370420/TestListView2.zip。我使用sysinternals DebugView來查看輸出。當我在列表中選擇多個項目時,只會觸發一個SelectItem事件並且SelCount爲0.如果我只選擇一個項目,則會觸發兩個事件。我在Windows 7 64位的另一臺計算機上測試了該項目,行爲相同。 – costa