Faking HideSelection Property for a TCheckListBox

106 19


The TCheckListBox Delphi control displays a scrollable list with check boxes next to each item. TCheckListBox is similar to TListBox, except that each item has a check box next to it. Users can check or uncheck items in the list.

Hide Selection

Even when you tab out of a check list box (where focus gets shifted to another control) there will still be a visual indicator for the selected item. The ItemIndex property determines which item is selected.
When using the TCheckListBox control, in most cases I am only interested in what items are checked.


The Checked[index] property indicates which items are checked. Checked is true if a check mark appears in the item's check box.

I am not interested in what is the selected item (if there is one) nor I want the visual indication of which item is selected when focus shifts to another control.

Solution: fake the HideSelection property found in some other list-style controls.

Intercepting TCheckListBox

The article Extend Delphi Components Without the Need to Install in the IDE explain how to create an interceptor class that has the same name as the class being extended.
Here it is:
type
  TCheckListBox = class(CheckLst.TCheckListBox)
  private
    fHideSelection : boolean;
  public
    property HideSelection : boolean read fHideSelection write fHideSelection;
    procedure ClickCheck; override;
    procedure DoExit; override;
  end;
Therefore we add a property HideSelection and override methods that will call OnClickCheck and OnClick event handlers:
procedure TCheckListBox.ClickCheck;
begin
  inherited;
  if HideSelection then ItemIndex := -1;
end;

procedure TCheckListBox.DoExit;
begin
  inherited;
  if HideSelection then ItemIndex := -1;
end;


Now, having a check list box with some items, a CheckBox determines if HideSelection is of or on:
procedure TTestForm.CheckBox1Click(Sender: TObject);
begin
  CheckListBox1.HideSelection := CheckBox1.Checked;
end;
That's it - now we have HideSelection for the TCheckListBox. Why all this when I could have just handled OnExit? Yes, far more easier approach is to just handle the OnExit event and set the ItemIndex property to -1. Even if you had dozens of check list boxes you could have applied the same event handler to OnExit for all of them.
Yet, I like it better like this ... feels more OOP.

Delphi tips navigator:
» Custom Hints For Each Tab in Delphi's TTabSet or TTabControl
« Remove Auto "&" in Menu Item's Caption

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.