[英]How to make DataGridViewLinkColumn underline and change background color
我有一个DataGridViewLinkColumn。如何将标题(row = -1)设置为下划线并更改其背景颜色
var WarningsColumn = new DataGridViewLinkColumn
{
Name = @"Warnings",
HeaderText = @"Warnings",
DataPropertyName = @"WarningsCount",
AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells,
ReadOnly = true
};
尝试这个:
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle
= new DataGridViewCellStyle {BackColor = Color.Yellow, Font = new Font(dataGridView1.Font, FontStyle.Underline)};
从DataGridView.ColumnHeadersDefaultCellStyle属性的MSDN参考中:
如果启用了视觉样式并将EnableHeadersVisualStyles设置为true,则使用当前主题绘制除TopLeftHeaderCell之外的所有标题单元格,并忽略ColumnHeadersDefaultCellStyle值。
因此,您可以将其设置为False
,然后覆盖默认值,然后您将得到如下所示的内容(进行快速而又肮脏的测试以确保其正常工作) :
编辑:
要将样式应用于单个列,请改用此样式(您希望将样式放在设置DataGridView
的DataSource
的代码之后):
dataGridView1.Columns["your_column_name"].HeaderCell.Style
= new DataGridViewCellStyle { BackColor = Color.Yellow, Font = new Font(dataGridView1.Font, FontStyle.Underline) };
我认为您必须像这样将自定义代码添加到CellPainting
事件处理程序中:
Point spot;
private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex > -1)
{
e.Handled = true;
if (e.CellBounds.Contains(spot))//Mouse over cell
{
PaintCellBackground(e.Graphics, Color.Red, e.CellBounds);
}
else //Mouse leave cell
{
PaintCellBackground(e.Graphics, Color.Green, e.CellBounds);
}
StringFormat sf = new StringFormat(){Alignment=StringAlignment.Center, LineAlignment = StringAlignment.Center };
Font f = new Font(e.CellStyle.Font, FontStyle.Underline);
e.Graphics.DrawString(e.Value.ToString(), f, new SolidBrush(e.CellStyle.ForeColor), e.CellBounds, sf);
}
}
private void PaintCellBackground(Graphics g, Color c, Rectangle rect)
{
Rectangle topHalf = new Rectangle(rect.Left, rect.Top, rect.Width, rect.Height / 2);
Rectangle bottomHalf = new Rectangle(rect.Left, topHalf.Bottom, rect.Width, topHalf.Height);
g.FillRectangle(new SolidBrush(Color.FromArgb(150, c)), topHalf);
g.FillRectangle(new SolidBrush(c), bottomHalf);
ControlPaint.DrawBorder(g, rect, Color.Gray, 1, ButtonBorderStyle.Solid,
Color.Gray, 0, ButtonBorderStyle.Solid,
Color.Gray, 1, ButtonBorderStyle.Solid,
Color.Gray, 0, ButtonBorderStyle.Solid);
}
//Reset spot when mouse leave
private void dataGridView_MouseLeave(object sender, EventArgs e)
{
spot = Point.Empty;
}
//Update spot when mouse move
private void dataGridView_MouseMove(object sender, MouseEventArgs e)
{
spot = e.Location;
}
看起来不好,但是可以帮助您入门,我认为默认背景会更好。 如果是这样,您只需要调用: e.PaintBackground(e.CellBounds, true);
自定义绘画应应用于DoubleBuffered控件。 因此,我认为您应该像这样创建自己的自定义DataGridView(仅是一些代码):
public class CustomDataGridView : DataGridView {
public CustomDataGridView(){
DoubleBuffered = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.