You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为DevExpress TcxGrid的聚焦行与选中行设置不同颜色?

为TcxGrid区分设置勾选记录与聚焦记录的颜色

要实现TcxGrid中复选框勾选的选中记录和当前聚焦记录的颜色区分,可通过DevExpress提供的事件结合样式系统或自定义绘制完成,以下是两种实用方案:

方案一:使用样式系统(推荐)

通过StyleRepository定义专属样式,在OnGetContentStyle事件中动态分配,更符合控件设计规范:

  1. 准备样式

    • 在组件面板拖入TcxStyleRepository,右键创建两个TcxStyle:
      • 命名为tsCheckedRow:设置Color为浅绿(如$00E0FFE0),Font.Color为黑色
      • 命名为tsFocusedRow:设置Color为浅蓝(如$00E0E0FF),Font.Color为深蓝
  2. 绑定GridView事件
    在GridView的OnGetContentStyle事件中添加逻辑:

    procedure TYourForm.cxGridTableView1GetContentStyle(Sender: TcxCustomGridTableView;
      ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
    begin
      // 优先判断是否为勾选的选中记录
      if Sender.Controller.SelectedRecords.Contains(ARecord) then
        AStyle := tsCheckedRow
      // 再判断是否为聚焦记录
      else if Sender.Controller.FocusedRecord = ARecord then
        AStyle := tsFocusedRow;
    end;
    

方案二:自定义绘制(灵活控制细节)

若需要更精细的绘制控制,可使用OnCustomDrawCell事件手动绘制单元格:

procedure TYourForm.cxGridTableView1CustomDrawCell(Sender: TcxCustomGridTableView;
  ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
  IsCheckedRow: Boolean;
  IsFocusedRow: Boolean;
begin
  IsCheckedRow := Sender.Controller.SelectedRecords.Contains(AViewInfo.RecordViewInfo.Record);
  IsFocusedRow := (Sender.Controller.FocusedRecord = AViewInfo.RecordViewInfo.Record);

  if IsCheckedRow then
  begin
    ACanvas.Brush.Color := $00E0FFE0;
    ACanvas.Font.Color := clBlack;
  end
  else if IsFocusedRow then
  begin
    ACanvas.Brush.Color := $00E0E0FF;
    ACanvas.Font.Color := clNavy;
  end;
end;

注意事项

  • 确保GridView的OptionsSelection.MultiSelect设为True,OptionsView.ShowCheckBoxes设为True,否则无法识别复选框勾选的记录
  • 若某行同时是聚焦且勾选状态,代码中优先应用勾选记录的样式,可根据需求调整判断顺序

内容的提问来源于stack exchange,提问作者Holy Thirteen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:35:06