限制Delphi上TCheckListBox的选中项

限制Delphi上TCheckListBox的选中项

本文介绍了限制Delphi上TCheckListBox的选中项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制一个TCheckListBox.我希望只应检查2个项目,并且所有未检查的项目都将被禁用并显示为灰色.由于选中/未选中的项目是动态的,因此我不能使用静态的itemIndex.

I want to limit a TCheckListBox.I desire only 2 items should be checked, and all unchecked items will be disabled and grayed.Since the checked / unchecked items are dynamic, i can not use a static itemIndex.

这是我尝试过的方法,但出现超出芯片范围"错误.

Here is what i tried, but i got "Out of chip bounds" error.

我的CheckListBox的单击事件;

On click event of my CheckListBox ;

var
  NumberOfCheckedItems, I: Integer;
begin
  NumberOfCheckedItems := 0;
  for I := 0 to CkLst1.Count - 1 do
  begin
    if CkLst1.Checked[I] then
      NumberOfCheckedItems := NumberOfCheckedItems + 1;
  end;
  if NumberOfCheckedItems > 1 then
  begin
    CkLst1.Checked[I] := Enabled;
    CkLst1.Enabled := FALSE;
    CkLst1.AllowGrayed := TRUE;
  end
  else
  begin
    //no idea
  end;
end;

推荐答案

此方法应能完成

procedure DoCheckListBox( AChkLb : TCheckListBox; AMaxCheck : Integer );
var
  LIdx : Integer;
  LCheckCount : Integer;
begin
  // counting
  LCheckCount := 0;
  for LIdx := 0 to AChkLb.Count - 1 do
  begin
    if AChkLb.Checked[LIdx] then
      if LCheckCount = AMaxCheck then
        AChkLb.Checked[LIdx] := False
      else
        Inc( LCheckCount );
  end;
  // enable/disable
  for LIdx := 0 to AChkLb.Count - 1 do
    AChkLb.ItemEnabled[LIdx] := AChkLb.Checked[LIdx] or ( LCheckCount < AMaxCheck );
end;

更新

您最好在 TCheckListBox.OnClickCheck 事件中调用此方法OnClick事件.双击可能会影响检查状态,但不会调用OnClick.每当检查状态更改时,都会调用OnClickCheck.

You better call this inside TCheckListBox.OnClickCheck event instead of OnClick event.A double-click can affect the check-state but OnClick is not called.OnClickCheck is called whenever the check-state changes.

这篇关于限制Delphi上TCheckListBox的选中项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:29