在Winforms DataGridView中显示CellPainting事件后的标题文本 [英] Display header text after CellPainting event in winforms datagridview
问题描述
我有一个datagridview控件,我想在每个标题单元格的底部放置一条3px的行,看起来像
I have a datagridview control where I want to put a 3px line at the bottom of each header cell to look something like
我已经在CellPainting中放置了代码,甚至对于datagridview也是如此:
I have put code in CellPainting even for the datagridview like:
if (e.RowIndex < 0) // headers
{
Rectangle newRect = new Rectangle(e.CellBounds.X, e.CellBounds.Y - 1 + e.CellBounds.Height, e.CellBounds.Width, 2);
using (Brush gridBrush = new SolidBrush(Color.Red))
{
e.Graphics.FillRectangle(gridBrush, newRect);
}e.Handled = true;
}
红线显示正确(稍后我将添加3px)。但是,现在缺少标题文本。
The red line appears correctly (I will add the 3px later). However, the header text now is missing.
我假设设置e.Handled = true;告诉不要继续绘制原始标题文本。如果将其设置为false,则红线消失。 (显然)此控件没有base.CellPainting类型的概念。
I am assuming that setting the e.Handled = true; tells to not continue to draw the original header text. If I set it to false, then the red line disappears. There is no base.CellPainting type concept for this control (apparently).
我知道我自己可以绘制文本,但随后我不得不担心对齐方式,字体。 ..
I know I can draw the text myself, but then I have to worry about alignment, font...
现在是否有办法告诉系统同时进行线条绘制原始标题文本?
Is there now way to tell the system to do both the line AND draw original header text?
如果必要,我愿意尝试其他方法。
I am willing to try other approaches if necessary.
推荐答案
此控件没有base.CellPainting类型概念。
确实; DGV不仅有调用基本事件的更多选择。
Indeed; the DGV has more options than just calling the base event.
相反,您可以让它分别绘制零件并按照需要的顺序进行操作:
Instead you can let it draw the parts separately and in the order you want:
if (e.RowIndex < 0) // headers
{
e.PaintBackground(e.CellBounds, true); // draw the default background
Rectangle newRect =
new Rectangle(e.CellBounds.X, e.CellBounds.Bottom - 2, e.CellBounds.Width, 2);
e.Graphics.FillRectangle(Brushes.Red, newRect); // now draw the red line
e.PaintContent(e.CellBounds); // finally draw the text in the default way
e.Handled = true; // done
}
如果您禁用 dgv.EnableHeadersVisualStyles
,您还可以设置绘制列标题时要使用的许多其他属性。
If you disable dgv.EnableHeadersVisualStyles
you can also set many other properties to be used when drawing the column headers..
对于更精细的调整您可能想研究的 MSDN 。
For even finer-tuned options you may want to look into MSDN.
这篇关于在Winforms DataGridView中显示CellPainting事件后的标题文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!