2016-11-22 10 views
2

TextRenderer.DrawTextを使用するCellPaintingイベントハンドラを実装していて、セルにアンパサンドが含まれるまではうまくいきました。セルは編集中にアンパサンドを正しく表示しますが、編集が完了して描画されると、小さな線(アンダースコアではありません)として表示されます。DataGridView CellPaintingアンパサンドで描画するテキストが奇妙に表示される

e.PaintContent(e.ClipBounds); 

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

を交換

Editing cell Not Editing cell

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"); 
    } 
} 

はそれを正しく示して、もちろん私はしかし、コンテンツの絵画をカスタマイズできるようにしたいです。 私も

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

e.PaintContent Image

を使用して試してみたが、それはセルがされているとき、私は私の実際のコードでe.Paintを使用

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

と同じ、それを描画しません。私のカスタマイズされた絵画は必要ありません。

にはどうすればe.Paintと同じように見えるかTextRenderer.DrawTextが正しくアンパサンドを表示するために取得するためにe.Graphics.DrawString得ることができますか?

答えて

3

あなたはひも付き本当に唯一の印刷に使用されなければならないので、TextRendererのバージョンを使用したい:

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

NOPREFIXフラグが正しく、アンパサンドが表示されます。

+0

素晴らしい!それはそれを修正! NoPrefixを使用しなければならない理由について何か説明がありますか?この "バグ"を最初に見つけなければ、私はそれを使わなければならないと私は思ったことがないでしょう。また、「印刷」という意味で、より明確に理解できますか? –

+0

@BlakeThingstadこれはバグではありません。アンパサンドは、あなたがボタンを作成するので、もし、それを有効にするには、ボタンでホット文字を表すために使用し、それを「&こんにちは」のtextプロパティを与えている、Hは下線されるだろう。 2つのアンパサンドは1つのみを表示するために使用されます。 – LarsTech

+2

@BlakeThingstad DrawStringには、多くの問題があり、それがTextRendererクラスに置き換えられました。しかし、DrawStringは、DPIの違いのために、紙への印刷にはまだ関連しています。すべてのMicrosoftコントロールはTextRendererクラスを使用します。より良い詳細な説明のために(http://stackoverflow.com/a/23230570/719186)[より良い品質を提供できる?TextRenderer.DrawText VS Graphics.drawStringを]この回答を参照してください。 – LarsTech

関連する問題