c# - 覆盖 DataGridViewTextBoxCell 绘制方法

标签 c# winforms

我试图在派生类中覆盖 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/

相关文章:

c# - Xamarin iOS,无法打开 Info.plist

c# - ITargetBlock<TInput> 中的重试策略

c# - 执行程序集中的相对路径

c# - 在 MVC 中设置 CaSTLe Windsor

c# - 如何比较两个富文本框内容并高亮显示变化的字符?

c# - 如何设置连接到主机 PC 的设备的 IP 地址? C# 窗体?

c# - 如何在外部浏览器中打开 webBrowser 控件中的链接?

c# - 停止在 winform 按钮上执行的功能单击

c# - 将 IConfiguration 注入(inject)到 .NET 6.0 上的 Windows 窗体

c# - ASP.net 通过内容页访问母版页变量