Delphi:在 DBGrid 中放置一个复选框(主题)

Delphi: Place a checkbox inside a DBGrid (themed)

我正在使用以下代码在 DBGrid 中显示一个复选框。它适用于(至少预期)主题和非主题 VCL 风格 (在 XE2、XE7 和柏林测试):

uses Vcl.Themes;

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
const
  CtrlState: Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED);
  CtrlStateXP: Array[Boolean] of TThemedButton = (tbCheckBoxUncheckedNormal, tbCheckBoxCheckedNormal);
var
  CheckBoxRectangle : TRect;
  Details: TThemedElementDetails;
begin
  if Column.Field.DataType = ftBoolean then
  begin
    Column.Title.Alignment := taCenter;
    Column.Alignment := taCenter;
    TDBGrid(Sender).Canvas.FillRect(Rect);

    if ThemeServices.ThemesEnabled then
    begin
      Details := ThemeServices.GetElementDetails(CtrlStateXP[Column.Field.AsBoolean]);
      ThemeServices.DrawElement(TDBGrid(Sender).Canvas.Handle, Details, Rect);
    end
    else
    begin
      CheckBoxRectangle.Left   := Rect.Left + 2;
      CheckBoxRectangle.Right  := Rect.Right - 2;
      CheckBoxRectangle.Top    := Rect.Top + 2;
      CheckBoxRectangle.Bottom := Rect.Bottom - 2;
      DrawFrameControl(TDBGrid(Sender).Canvas.Handle, CheckBoxRectangle, DFC_BUTTON, CtrlState[Column.Field.AsBoolean]);
    end;
  end;
end;

它工作正常,除了当我在行上移动时,样式变成 'strange',如下所示:

有什么帮助吗? 谢谢

经过一些尝试和研究,我设法自己调整了该方法,只需添加以下几行:

  if not (gdFocused in State) then
    Grid.Canvas.Brush.Color := StyleServices.GetSystemColor(clHighlight);

这里分享完整的方法。它可能对某人有用:-)

uses Vcl.Themes;

procedure CheckBoxGrid(FieldName: String; ValueCheck: Variant; Grid: TDBGrid; const Rect: TRect; Column: TColumn; State: TGridDrawState);
const
  CtrlState: Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED);
  CtrlStateXP: Array[Boolean] of TThemedButton = (tbCheckBoxUncheckedNormal, tbCheckBoxCheckedNormal);
var
  R: TRect;
  Details: TThemedElementDetails;
begin
  if Column.FieldName = FieldName then
  begin
    Column.Title.Alignment := taCenter;
    Column.Alignment := taCenter;
    Grid.Canvas.FillRect(Rect);

    if StyleServices.Enabled then
    begin
      Details := StyleServices.GetElementDetails(CtrlStateXP[Column.Field.Value = ValueCheck]);
      StyleServices.DrawElement(Grid.Canvas.Handle, Details, Rect);

      if not (gdFocused in State) then
        Grid.Canvas.Brush.Color := StyleServices.GetSystemColor(clHighlight);
    end
    else
    begin
      R := Rect;
      InflateRect(R, -2, -2);
      DrawFrameControl(Grid.Canvas.Handle, R, DFC_BUTTON, CtrlState[Column.Field.Value = ValueCheck]);
    end;
  end;
end;​