我需要根据是否在列表中至少选择了一行来启用或禁用按钮。
以下是重现此问题的代码。该列表使用 OnData 事件填充,它允许选择多行。
我认为我可以使用 OnSelectItem 来检测用户何时更改选择,然后使用 TListView SelCount 函数来检测所选行数。
问题是当用户选择多行时 SelCount 返回 0。如果手动填充列表(即不是通过 OnData 事件),这可以正常工作。
有任何想法吗?
谢谢
更新:使用 OnChange 事件似乎可以解决问题。理解为什么 SelCount 在选择多行时返回 0(从 SelectItem 事件中)仍然会很有趣。
另一个更新:我发布了一个测试项目:https ://dl.dropboxusercontent.com/u/35370420/TestListView2.zip以及截图:
要重现此问题,请运行应用程序,选择 Item1,然后 SHIFT+单击 Item2。该按钮被禁用。我的意图是只要在列表中至少选择了一项,就可以动态启用该按钮。如果没有选定的项目,则该按钮被禁用。
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