2

我需要将我的货币单元格放在网格上以显示当地货币符号,右对齐并以红色显示负数。

与类似的帖子不同,我使用实时绑定从数据集中填充我的 TGrid。其他解决方案建议从 TStringCell 为网格子分类“TFinancialCell”,这在使用实时绑定时很困难。

使用 Livebindings,绑定管理器控制网格列和单元格的创建,因此对绑定管理器(和其他相关类)进行子类化可能既不实用也不优雅。

4

1 回答 1

3

再搞砸了一些,我找到了一个解决我的问题的解决方案

货币符号是通过使用数据集字段的 OnGetText 事件返回格式化字符串获得的:

procedure FDTableMyCurrFieldGetText(Sender: TField; var Text: string;
  DisplayText: Boolean);
begin
  DisplayText := True;
  Text := FloatToStrF(Sender.AsCurrency, ffCurrency, 18, 2);
end;

我本可以在 Grid OnPainting 事件中完成此操作,但这样做会格式化所有链接控件以及网格的字段。我使用“Sender”而不是“FDTableMyCurrField”来引用字段,以便我可以将数据集中所有其他货币字段的 OnGetText 事件指向此方法。

其余的格式化在网格中完成。网格的单元格没有显式公开,但您可以像这样“TTextCell(Grid1.Columns[I].Children[J])”来获取它们。在绘制单元格之前,使用 Grid OnPainting事件对其进行格式化。

右对齐是通过设置网格中单元格的对齐方式来实现的。

使用样式设置单元格文本颜色。我们需要在我们的应用程序样书中创建一个“textcellnegativestyle”。这将与默认的“textcellstyle”相同,只是“前景”画笔颜色为红色。在桌面应用程序上,您可以在应用程序上放置一个 TEdit,右键单击它并选择“编辑自定义样式...”,然后根据“editstyle”将自定义样式命名为“textcellnegativestyle”,但只需将前景画笔颜色更改为红色.

我的是一个移动应用程序,由于这个原因,Delphi 表单编辑器弹出菜单选项中没有出现“编辑自定义样式” 。要添加自定义样式,您必须使用记事本或某些文本编辑器编辑(副本).style 文件。

  1. 复制/粘贴“textcellstyle”对象
  2. 将粘贴对象的名称编辑为“textcellnegativestyle”
  3. 将“前景”画笔颜色更改为红色。
  4. 将编辑后的文件加载到您的应用程序样书中。

这是它在我的 .style 文件中的外观:

  object TLayout
    StyleName = 'textcellnegativestyle'
    DesignVisible = False
    Height = 50.000000000000000000
    Width = 50.000000000000000000
    object TLayout
      StyleName = 'content'
      Align = alContents
      Locked = True
      Height = 42.000000000000000000
      Margins.Left = 4.000000000000000000
      Margins.Top = 4.000000000000000000
      Margins.Right = 4.000000000000000000
      Margins.Bottom = 4.000000000000000000
      Width = 42.000000000000000000
    end
    object TBrushObject
      StyleName = 'foreground'
      Brush.Color = claRed
    end
    object TBrushObject
      StyleName = 'selection'
      Brush.Color = x7F72B6E6
    end
    object TFontObject
      StyleName = 'font'
    end
  end

我使用 Grid OnPainting 事件来设置单元格对齐方式和样式。这是我的工作解决方案:

procedure TFormMain.Grid1Painting(Sender: TObject; Canvas: TCanvas;
  const ARect: TRectF);
var
  I, J: Integer;
  T: TTextCell;
begin
  // my Column 0 is text, all other columns are money in this example
  for I := 1 to Grid1.ColumnCount - 1 do
    for J := 0 to Grid1.Columns[I].ChildrenCount- 1 do
    begin
      T := TTextCell(Grid1.Columns[I].Children[J]);
      // set the Cell text alignment to right align
      T.TextAlign := TTextAlign.taTrailing;

      // test the Cell string for a negative value
      if (T.Text[1] = '-') then
      begin
        // remove the leading minus sign
        T.Text := Copy(T.Text, 2, Length(T.Text) - 1);
        // set the font to red using the style
        T.StyleLookup := 'textcellnegativestyle';
      end
      else T.StyleLookup := 'textcellstyle';
    end;
end;
于 2013-11-05T08:16:10.957 回答