我试图在派生类中覆盖 DataGridViewTextBoxCell 的绘制方法,以便我可以将前景文本缩进一些可变的像素数量。如果调整列的宽度使其总宽度是我的单元格文本的长度加上“缓冲区”缩进,我会喜欢它。有谁知道实现这一目标的方法?下面列出了我蹩脚的实现:
public class MyTextBoxCell : DataGridViewTextBoxCell{ ....
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) {
clipBounds.Inflate(100, 0);
DataGridViewPaintParts pp = DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground
| DataGridViewPaintParts.ErrorIcon;
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, pp);
string text = formattedValue as string;
//My lame attempt to indent 20 pixels??
TextRenderer.DrawText(graphics, text, cellStyle.Font, new Point(cellBounds.Location.X + 20, cellBounds.Location.Y), cellStyle.SelectionForeColor ,TextFormatFlags.EndEllipsis);
}
最佳答案
您可以连接到数据 GridView 中的 CellFormattingEvent 并在那里进行格式化。或者,如果您从 DataGridView 继承,您可以只覆盖 OnCellFormatting 方法。代码看起来像这样:
if (e.ColumnIndex == 1)
{
string val = (string)e.Value;
e.Value = String.Format(" {0}", val);
e.FormattingApplied = true;
}
只是一些粗略的代码,但您明白了。
关于c# - 覆盖 DataGridViewTextBoxCell 绘制方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/177133/