2
我已經實現了一個使用TextRenderer.DrawText的CellPainting事件處理程序,它的工作效果非常好,直到一個單元格中有一個&符。單元格在編輯單元格時正確顯示了&符號,但編輯完成並繪製後,它顯示爲一個小行(不是下劃線)。DataGridView 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正確顯示&符號?
令人驚歎!這解決了它!你有任何解釋爲什麼NoPrefix必須使用?我永遠不會猜到,如果不先找到這個「bug」,我就不得不使用它。另外,你可以通過「印刷」來表達你的意思嗎? –
@BlakeThingstad這不是一個錯誤。 「&」符號用於表示按鈕中的熱字母以激活它,因此如果您創建一個按鈕併爲其指定了「&Hello」的文本屬性,則H將加下劃線。兩個&號將用於僅顯示一個。 – LarsTech
@BlakeThingstad DrawString在監視器上繪製文本時遇到了很多問題,因此它將替換爲TextRenderer類。但由於DPI的差異,DrawString仍然適用於打印到紙張。所有的Microsoft控件都使用TextRenderer類。看到這個答案[Graphics.DrawString vs TextRenderer.DrawText?它可以提供更好的質量](http://stackoverflow.com/a/23230570/719186)更好的詳細解釋。 – LarsTech