带有&符号的DataGridView CellPainting绘图文本很奇怪

Bla*_*tad 3 c# datagridview winforms

我已经实现了一个使用TextRenderer.DrawText的CellPainting事件处理程序,它已经很好地工作,直到一个单元格中有一个&符号.单元格在编辑单元格时正确显示&符号,但是在完成编辑并绘制它时,它会显示为一条小线(不是下划线).

编辑单元格 不编辑单元格

using System;
using System.Drawing;
using System.Windows.Forms;

namespace StackOverFlowFormExample {
    public partial class DataGridViewImplementation : DataGridView {
        public DataGridViewImplementation() {
            InitializeComponent();
            this.ColumnCount = 1;
            this.CellPainting += DGV_CellPainting;
        }

        private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {         
            if (!e.Handled && e.RowIndex > -1 && e.Value != null) {
                e.PaintBackground(e.CellBounds, false);
                TextRenderer.DrawText(e.Graphics, e.Value.ToString(), 
                                      e.CellStyle.Font, e.CellBounds,
                                      e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
                e.Handled = true;
            }
        }
    }
}

//creating the datagridview
public partial class MainForm : Form {
    public MainForm() {
        InitializeComponent();  
        DataGridViewImplementation dgvi = new DataGridViewImplementation();
        this.Controls.Add(dgvi);
        dgvi.Rows.Add("this is a & value");
    }
}
Run Code Online (Sandbox Code Playgroud)

更换

TextRenderer.DrawText(e.Graphics, e.Value.ToString(), 
                      e.CellStyle.Font, e.CellBounds, 
                      e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
Run Code Online (Sandbox Code Playgroud)

e.PaintContent(e.ClipBounds);
Run Code Online (Sandbox Code Playgroud)

正确地显示它,当然我希望能够自定义内容的绘画.我也试过用

e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds);
Run Code Online (Sandbox Code Playgroud)

e.PaintContent图像

但它并没有像它那样画出来

e.Paint(e.ClipBounds, e.PaintParts);
Run Code Online (Sandbox Code Playgroud)

当我正在绘制一个不需要我自定义绘画的单元格时,我在实际代码中使用了e.Paint.

如何使e.Graphics.DrawString看起来与e.Paint相同或获取TextRenderer.DrawText以正确显示&符号?

Lar*_*ech 6

您想使用TextRenderer版本,因为DrawString实际上只能用于打印:

TextRenderer.DrawText(e.Graphics, e.Value.ToString(), 
                  e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, 
                  TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter);
Run Code Online (Sandbox Code Playgroud)

NoPrefix标志将正确显示&符号.

  • @BlakeThingstad DrawString在监视器上绘制文本有很多问题,因此它将替换为TextRenderer类.但由于DPI差异,DrawString仍然与打印到纸张相关.所有Microsoft控件都使用TextRenderer类.请参阅此答案[Graphics.DrawString vs TextRenderer.DrawText?哪个可以提供更好的质量](http://stackoverflow.com/a/23230570/719186)以获得更详细的解释. (3认同)
  • @BlakeThingstad这不是错误。“&”号用于表示按钮中的热字母以激活它,因此,如果您创建一个按钮并将其文本属性设置为“&Hello”,则将在下划线处加上H。两个“&”号仅用于显示一个。 (2认同)