2

我正在为 VSTS2010 的 AddIn 覆盖 DataGridView 的 CellPainting 事件。基本上我有两行数据,我希望第一行是黑色的,第二行是灰色的。这一切都很好,但有时,我无法确定,有时单元格内容会被绘制到左侧约 50 像素,并从应有的位置向上绘制 5 像素。例如: 例子

突出显示的文件名是 ExecutionHints.cs,但您只能看到“nHints.cs”

这发生在 1 次 VSTS 会话中,3 次,或者有时只是在下午的某个时间点进行 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();
}
4

0 回答 0