在使用 DBGrid 顯示大量欄位時,開發者常面臨兩難:若不啟用 dgRowSelect,水平滾動到右側時容易看錯行;若啟用 dgRowSelect,點擊非當前行會導致視圖跳回最左列,使用者必須反覆拖動滾動條。如何同時擁有「整行高亮」與「可直接編輯」的體驗?
取消 DBGrid->Options[dgRowSelect],改用 OnDrawColumnCell 事件在繪製時將當前行背景填成藍色、字體變白,視覺上彷彿整行被選中,實際上仍處於單元格編輯模式。這招「曲線救國」在 Delphi 中因單元封裝機制(同單元類別互為友元)可直接存取 TDBGrid 的 protected 欄位 DataLink 與 Row。
C++ 無單元級友元,需用「繼承暴露法」:在事件處理函式內部定義兩個繼承類別,分別將 TCustomGrid::Row 與 TCustomDBGrid::DataLink 以 __property 公開,再以 Sender 強制轉型存取。
void __fastcall TMainForm::LineSelEdit(TObject *Sender, const TRect &Rect, int DataCol, TColumn *Column, TGridDrawState State)
{
class TMyGridBase : public TCustomGrid { public: __property Row; };
class TMyGrid : public TCustomDBGrid { public: __property DataLink; };
TMyGrid *MyGrid = (TMyGrid*)Sender;
TMyGridBase *MyGridBase = (TMyGridBase*)Sender;
TDBGrid *Grid = (TDBGrid*)Sender;
if (MyGrid->DataLink->ActiveRecord == MyGridBase->Row - 1) {
Grid->Canvas->Font->Color = clWhite;
Grid->Canvas->Brush->Color = TColor(0x00800040);
} else {
Grid->Canvas->Brush->Color = Grid->Color;
Grid->Canvas->Font->Color = Grid->Font->Color;
}
Grid->DefaultDrawColumnCell(Rect, DataCol, Column, State);
}
DBGrid->Options >> dgRowSelectDBGrid->DefaultDrawing = falseOnDrawColumnCell 事件中呼叫上述函式此法完美解決「滾動不跳列、點擊即編輯、視覺仍整行高亮」的三重需求,且無需第三方元件。