【发布时间】:2010-12-21 08:15:37
【问题描述】:
如何更改 ListView 的 Headers 的背景颜色?
【问题讨论】:
-
您需要通过覆盖 Paint 事件来实现自定义绘图。
-
覆盖 Paint 方法对 ListView 没有任何作用。您需要使用@David 建议的 OwnerDraw 机制。请记住,这样做会从您的标题控件中删除所有样式——没有热门项目、没有排序指示器、没有渐变背景。
如何更改 ListView 的 Headers 的背景颜色?
【问题讨论】:
您可以通过将列表视图的 OwnerDraw 属性设置为 true 来做到这一点。
这允许您为列表视图的绘制事件提供事件处理程序。
MSDN上有详细的例子
下面是一些将标题颜色设置为红色的示例代码:
private void listView1_DrawColumnHeader(object sender,
DrawListViewColumnHeaderEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Red, e.Bounds);
e.DrawText();
}
我认为(但很高兴被证明是错误的)将 OwnerDraw 设置为 true,您还需要为其他具有默认实现的绘图事件提供处理程序,如下所示:
private void listView1_DrawItem(object sender,
DrawListViewItemEventArgs e)
{
e.DrawDefault = true;
}
如果没有它,我当然无法让列表视图绘制项目。
【讨论】:
我知道这对聚会来说有点晚了,但我仍然看到了这篇文章,这会对我有所帮助。这是 david 提供的代码的一点抽象应用
using System.Windows.Forms;
using System.Drawing;
//List view header formatters
public static void colorListViewHeader(ref ListView list, Color backColor, Color foreColor)
{
list.OwnerDraw = true;
list.DrawColumnHeader +=
new DrawListViewColumnHeaderEventHandler
(
(sender, e) => headerDraw(sender, e, backColor, foreColor)
);
list.DrawItem += new DrawListViewItemEventHandler(bodyDraw);
}
private static void headerDraw(object sender, DrawListViewColumnHeaderEventArgs e, Color backColor, Color foreColor)
{
using (SolidBrush backBrush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(backBrush, e.Bounds);
}
using (SolidBrush foreBrush = new SolidBrush(foreColor))
{
e.Graphics.DrawString(e.Header.Text, e.Font, foreBrush, e.Bounds);
}
}
private static void bodyDraw(object sender, DrawListViewItemEventArgs e)
{
e.DrawDefault = true;
}
然后在表单构造函数中调用它
public Form()
{
InitializeComponent();
*CLASS NAME*.colorListViewHeader(ref myListView, *SOME COLOR*, *SOME COLOR*);
}
只需将 *CLASS NAME* 替换为您将第一个代码放入的任何类,并将 *SOME COLOR* 替换为某种颜色。
//Some examples:
Color.white
SystemColors.ActiveCaption
Color.FromArgb(0, 102, 255, 102);
【讨论】: