首先对属性OwnerDraw设置为true:
private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.Columns.Add("Name");
listView1.Columns.Add("Age");
listView1.Columns.Add("Id");
listView1.Items.Add(new ListViewItem(new string[] { "John ", "15", "1001" }));
listView1.Items.Add(new ListViewItem(new string[] { "Jack ", "18", "1002" }));
listView1.Items.Add(new ListViewItem(new string[] { "Json ", "19", "1003" }));
listView1.OwnerDraw = true;
}
其次,完成下面两个事件的处理:
第一个事件是对列头的字体、底色处理
private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
if(e.ColumnIndex %2 ==1)//列的序号为单列的处理,1/3/5
{
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
e.DrawBackground();
e.Graphics.FillRectangle(Brushes.Pink, e.Bounds); //设置背景颜色
Font font = new Font("Arial",8,FontStyle.Bold); //设置字体大小
e.Graphics.DrawString(e.Header.Text, font, Brushes.Black, e.Bounds, format); //设置字体颜色
}
else//列的序号为双列的处理,0/2/4
{
//类似
}
}
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
e.DrawBackground();//背景色保留,若不添加该语句,则其他地方对ListView的底色处理会不生效
e.DrawText();//若不添加该语句,则ListView内容为空,无法刷新,其他地方对ListView的赋值会不生效
}
效果如下: