winforms 如何更改listView ColumnHeader文本颜色?

uidvcgyl  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(122)

在form1构造函数中

listView1.Scrollable = true;
listView1.View = View.Details;
ColumnHeader header = new ColumnHeader();
            
header.Text = "Files are ready";
header.Name = "col1";
listView1.Columns.Add(header);
            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

我想将“文件已就绪”的颜色更改为红色。因此我尝试使用此事件:

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            using (var sf = new StringFormat())
            {
                sf.Alignment = StringAlignment.Center;

                using (var headerFont = new Font("Microsoft Sans Serif", 9, FontStyle.Bold))
                {
                    e.Graphics.FillRectangle(Brushes.Pink, e.Bounds);
                    e.Graphics.DrawString(e.Header.Text, headerFont,
                        Brushes.Black, e.Bounds, sf);
                }
            }
        }

已尝试将两个画笔都更改为红色,但没有任何更改。

o7jaxewo

o7jaxewo1#

您可能没有将listView1OwnerDraw属性设置为true
此属性指示您希望通过自己的代码而不是原始的ListView方法绘制ListView的一部分。如果没有此属性,ListView将不会引发DrawColumnHeaderDrawItemDrawSubItem等事件。
对于您不想自己绘制的列,请将e.DrawDefault设置为true。如果您只想更改文本颜色,请使用e.DrawBackground()绘制标题的背景:

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    if (e.ColumnIndex != myColumnIndex)
    {
        e.DrawDefault = true; // tell the ListView to draw this header
        return;
    }

    e.DrawBackground();

    // draw your text as you did in your code
    // except the FillRectangle since the background is
    // now already drawn
}

但是如果你把listView1.OwnerDraw设置为trueListView会询问你所有的信息:头、项和子项。因此,您还需要订阅DrawItemDrawSubItem事件,并明确告诉ListView您希望它自己绘制这些内容:

listView1.DrawItem += (sender, e) => { e.DrawDefault = true; };
listView1.DrawSubItem += (sender, e) => { e.DrawDefault = true; };

相关问题