ListView DrawColumnHeader无法正常工作

时间:2015-11-22 19:53:40

标签: c# winforms listview

我有以下方法为列表视图的列标题设置背景颜色和字体,但它不起作用。有人可以帮帮我吗?

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    using (StringFormat sf = new StringFormat())
    {
        // Store the column text alignment, letting it default
        // to Left if it has not been set to Center or Right.
        switch (e.Header.TextAlign)
        {
            case HorizontalAlignment.Center:
                sf.Alignment = StringAlignment.Center;
                break;
            case HorizontalAlignment.Right:
                sf.Alignment = StringAlignment.Far;
                break;
        }

        // Draw the standard header background.
        e.DrawBackground();

        // Draw the header text.
        using (Font headerFont = new Font("Helvetica", 25, FontStyle.Bold)) //Font size!!!!
        {
            e.Graphics.DrawString(e.Header.Text, headerFont, Brushes.Black, e.Bounds, sf);
        }
    }
    return;
}

我使用这种方法并不重要。它保持不变。没有什么变化。 是因为列表视图的属性吗?

1 个答案:

答案 0 :(得分:4)

您的代码看起来不错。如果它没有做任何事情,您忘记将OwnerDraw属性设置为true

这也意味着您需要其他两个绘制事件添加代码。默认操作将执行:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
}


private void listView1_DrawSubItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
}

别忘了hook up事件; - )