ListView DrawColumnHeader不起作用

本文关键字:不起作用 DrawColumnHeader ListView | 更新日期: 2023-09-27 18:23:55

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

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;
}

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

ListView DrawColumnHeader不起作用

您的代码看起来不错。如果它不起任何作用,您就忘记了将OwnerDraw属性设置为true

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

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

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

别忘了把事件联系起来;-)