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

时间:2017-03-16 13:40:24

标签: delphi checkbox themes dbgrid

我使用以下代码在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;

它工作得很好,除非我在行上移动时,风格变得“奇怪”,就像吼叫:

themed issue

有任何帮助吗? 感谢。

1 个答案:

答案 0 :(得分:1)

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

  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;​