以下更改 TInplaceEdit 背景颜色的代码在 Delphi 2010 中有效,但在 Delphi 2011 Community Edition 中无效。然而 CharCase 确实有效。我查看了许多解决此问题的示例,但没有一个对我有用。我做错了什么?
type
TMyInplaceEdit = class(TInplaceEdit)
public
property Color; //redeclare to make public
constructor Create(AOwner: TComponent); override;
end;
TTestGrid = class(TStringGrid)
public
property InplaceEditor; //redeclare to make public
function CreateEditor: TInplaceEdit; override;
end;
TForm1 = class(TForm)
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
TestGrid: TTestGrid;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TMyInplaceEdit.Create(AOwner: TComponent);
begin
inherited;
Color := clMoneyGreen;
CharCase := ecUpperCase;
end;
function TTestGrid.CreateEditor: TInplaceEdit;
begin
inherited;// same without this line
Result := TMyInplaceEdit.Create(self);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
TestGrid := TTestGrid.Create(Self);
TestGrid.Parent := Self;
TestGrid.Show;
TestGrid.Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goEditing, goTabs];
end;
首先,没有 Delphi 2011,更不用说它的社区版了。第一个社区版是 10.2 Tokyo。也许您指的是 Delphi 11(即当前的社区版)?
无论如何,编辑器的
Color
被忽略的原因是,在 CreateEditor()
返回后,网格将编辑器的 Color
设置为与网格的 Color
匹配(它还设置编辑器的 Font
和 StyleElements
)
也与网格相匹配)。
此行为是在 Delphi XE3 中添加的,这就是为什么它在 Delphi 2010 中不会发生。
每次网格更新编辑器时,它都会重置
Color
(以及 Font
和 StyleElements
)以匹配网格的值,从而使按照您想要的方式自定义编辑器变得更加困难。我能够通过让编辑器处理 CM_COLORCHANGED
通知并将其颜色更改回 clMoneyGreen
来实现你想要的,例如:
type
TMyInplaceEdit = class(TInplaceEdit)
protected
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
...
end;
procedure TMyInplaceEdit.CMColorChanged(var Message: TMessage);
begin
// this 'inherited' IS needed, or else the color won't draw correctly!
inherited;
// this 'if' is not needed, as TControl.SetColor() is
// reentrant-safe, so this will NOT cause a recursive loop
//if Color <> clMoneyGreen then
Color := clMoneyGreen;
end;