我有一个DataGridViewLinkColumn.How我可以做头(行= -1)为下划线,并改变它的背景颜色
var WarningsColumn = new DataGridViewLinkColumn
{
Name = @"Warnings",
HeaderText = @"Warnings",
DataPropertyName = @"WarningsCount",
AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells,
ReadOnly = true
};
我认为你必须自定义代码添加到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);
UPDATE
在风俗画应该DoubleBuffered控制应用。 所以,我认为你应该这样创建自己的自定义的DataGridView(它只是一点点更多的代码):
public class CustomDataGridView : DataGridView {
public CustomDataGridView(){
DoubleBuffered = true;
}
}
尝试这个:
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle
= new DataGridViewCellStyle {BackColor = Color.Yellow, Font = new Font(dataGridView1.Font, FontStyle.Underline)};
从在MSDN参考DataGridView.ColumnHeadersDefaultCellStyle属性 :
如果启用视觉样式和EnableHeadersVisualStyles设置为true,所有标题单元格除了TopLeftHeaderCell使用的是当前的主题画和ColumnHeadersDefaultCellStyle值将被忽略。
所以,你可以将它设置为False
,然后覆盖默认值,然后你会拥有这样的事情(快速和肮脏的测试,以确保它的工作原理):
编辑:
要应用样式到一列,用这个来代替(你会希望你设置的密码后,把这个DataSource
中的DataGridView
):
dataGridView1.Columns["your_column_name"].HeaderCell.Style
= new DataGridViewCellStyle { BackColor = Color.Yellow, Font = new Font(dataGridView1.Font, FontStyle.Underline) };