我在AddIn for VSTS2010中覆盖了DataGridView的CellPainting事件。基本上我有2行数据,我希望第一行是黑色,第二行是灰色。这一切都运行得很好,但有时候,我无论如何都无法分辨,有时单元格内容将被绘制在左边大约50个像素和距离应该的位置5个像素。 例如:
高亮显示的文件名是ExecutionHints.cs,但你只能看到“nHints.cs”
这种情况发生在3个VSTS会话中,或者有时仅在下午的某个时间点进行1个会话。它似乎没有发生的模式。
我尝试过使用e.CellBounds.X甚至硬编码“2”作为DrawString的X位置,但它仍然会发生。当它发生并且值正确时我附加了一个调试器,即Value ==“ExecutionHints.cs”,e.CellBounds.X == 1,e.ClipBounds.X == 0.
有什么想法吗?建议尝试?
代码:
private void grdFiles_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (grdFiles.Columns[e.ColumnIndex].Name != clmDisplay.Name || e.RowIndex < 0) return;
var lines = new string[] { "", "" };
SolidBrush backColorBrush;
var selected = (DataGridViewElementStates.Selected & e.State) == DataGridViewElementStates.Selected;
// Get back colour depending on cell contents.
if (e.Value != null)
{
lines = System.Text.RegularExpressions.Regex.Split(e.Value.ToString(), Environment.NewLine);
backColorBrush = selected ? new SolidBrush(e.CellStyle.SelectionBackColor) : GetBackBrushColor(lines[1]);
}
else
backColorBrush = new SolidBrush(selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
using (Brush gridBrush = new SolidBrush(this.grdFiles.GridColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
// Draw the grid lines (only the right and bottom lines;
// DataGridView takes care of the others).
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
e.CellBounds.Top, e.CellBounds.Right - 1,
e.CellBounds.Bottom);
// Draw the text content of the cell, ignoring alignment.
if (e.Value != null)
{
e.Graphics.DrawString(lines[0], e.CellStyle.Font, Brushes.Black, 2, e.CellBounds.Y + 2, StringFormat.GenericDefault);
e.Graphics.DrawString(lines[1], e.CellStyle.Font, selected ? Brushes.White : Brushes.Gray, 2, e.CellBounds.Y + 18, StringFormat.GenericDefault);
}
e.Handled = true;
}
}
backColorBrush.Dispose();
}