日期:2014-05-18  浏览次数:20905 次

请教如何重绘DataGridView列头的样式?
vs2005中c#写的winform程序,用到了很多DataGridView,想把灰色的列头(ColumnHeader)换成那种色彩渐变带有水晶效果的样式,不知道如何重绘?我开始在paint事件里在头的位置画一个列头覆盖原来的,可点击头时有闪动,可能是下面的位置本来已经绘制好了而我又画了一个的原因。后来干脆让DataGridView本身的列头不显示,就显示我手动绘制的那个,又觉得这样不太好。想问下大家我如何override绘制头的事件?或者到底怎么写最好?最好能提供一段源码,谢谢了!

------解决方案--------------------
可以处理CellPainting事件。当事件参数中的RowIndex是-1时,画的是表头:

C# code

    public Form1()
    {
        InitializeComponent();
        this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
    }

    void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex == -1)
        {
            bool mouseOver = e.CellBounds.Contains(dataGridView1.PointToClient(Cursor.Position));
            LinearGradientBrush brush = new LinearGradientBrush(
                e.CellBounds,
                mouseOver ?  Color.PeachPuff : Color.LightGray,
                Color.DarkOrange, 
                LinearGradientMode.Vertical);

            using(brush)
            {
                e.Graphics.FillRectangle( brush, e.CellBounds);
                Rectangle border = e.CellBounds;
                border.Width -= 1;
                e.Graphics.DrawRectangle( Pens.Gray, border);
            }

            e.PaintContent(e.CellBounds);
            e.Handled = true;
        }
    }

------解决方案--------------------
唯一的可能性,你有隐藏列