【问题标题】:DataGridView CellPainting drawing text with ampersand displays weirdlyDataGridView CellPainting 带有 & 符号的绘图文本显示奇怪
【发布时间】:2016-11-22 23:17:18
【问题描述】:

我已经实现了一个使用 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");
    }
}

替换

TextRenderer.DrawText(e.Graphics, e.Value.ToString(), 
                      e.CellStyle.Font, e.CellBounds, 
                      e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);

与

e.PaintContent(e.ClipBounds);

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

e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds);

但它的画法并不像

e.Paint(e.ClipBounds, e.PaintParts);

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

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

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您想使用 TextRenderer 版本,因为 DrawString 应该只用于打印:

    TextRenderer.DrawText(e.Graphics, e.Value.ToString(), 
                      e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, 
                      TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter);
    

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

    【讨论】:

    • 太棒了!那解决了它!您对为什么必须使用 NoPrefix 有任何解释吗?我永远不会猜到我必须在没有首先找到这个“错误”的情况下使用它。另外,您所说的“打印”是什么意思能更清楚吗?
    • @BlakeThingstad 这不是错误。 & 符号用于表示按钮中的热字母以激活它,因此如果您创建一个按钮并给它一个文本属性“&Hello”,那么 H 将带有下划线。两个&符号将用于仅显示一个。
    • @BlakeThingstad DrawString 在监视器上绘制文本时遇到了很多问题,因此将其替换为 TextRenderer 类。但由于 DPI 差异,DrawString 仍然适用于打印到纸上。所有 Microsoft 控件都使用 TextRenderer 类。请参阅此答案Graphics.DrawString vs TextRenderer.DrawText?Which can Deliver Better Quality 以获得更好的详细说明。
    猜你喜欢
    • 2019-07-22
    • 2014-09-04
    • 1970-01-01
    • 2011-12-23
    • 2014-11-14
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多