如何设置ListView控件中的列头的颜色(含标题列居中问题)!

转自https://www.cnblogs.com/chuncn/archive/2009/07/13/1522594.html

http://www.datazx.cn/dotnetframeworkyibanxingwentitao/2018082553/csharpsharp35774bsharp32622blistviewsharp3

整理如下:

将listview 的OwnerDraw 属性设置为 true 并且将 View 属性设置为 View. Details 时,将触发

ListViewDrawColumnHeader事件(包括ListView DrawItem事件、ListView DrawSubItem事件)自己画背景色,下面代码可以分别对3个列头(ColumnHeader)进行重画,Item与SubItem未进行重画.

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
	if (e.ColumnIndex == 0)
	{
		e.Graphics.FillRectangle(Brushes.DarkGray, e.Bounds);	//采用特定颜色绘制标题列,这里我用的灰色
		e.DrawText();	//采用默认方式绘制标题文本
	}
	
	else if (e.ColumnIndex == 1)
	{
		e.Graphics.FillRectangle(Brushes.DarkGray, e.Bounds);	//采用特定颜色绘制标题列,这里我用的灰色
		e.DrawText();	//采用默认方式绘制标题文本
	}

	else if (e.ColumnIndex == 2)
	{
		e.Graphics.FillRectangle(Brushes.DarkGray, e.Bounds);	//采用特定颜色绘制标题列,这里我用的灰色
		e.DrawText();	//采用默认方式绘制标题文本
	}
}

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
	e.DrawDefault = true; //采用系统默认方式绘制项
}

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
	e.DrawDefault = true; //采用系统默认方式绘制项
}

如需对Item与SubItem进行重画,参见下面代码

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
      e.Graphics.FillRectangle(Brushes.Red, e.Bounds);	//采用特定颜色绘制标题列,这里我用的红色
      e.DrawText();	//采用默认方式绘制标题文本
}

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
      e.Graphics.FillRectangle(Brushes.Red, e.Bounds);	//采用特定颜色绘制标题列,这里我用的红色
      e.DrawText();	//采用默认方式绘制标题文本
}

标题列居中,将listview 的OwnerDraw 属性设置为 true后,标题列的对齐方式代码将生效;

如果listview 的OwnerDraw 属性设置为 false,标题列的对齐方式代码将无法改变(始终为左对齐)。

具体参见下面的代码:

this.listView1.OwnerDraw = true; //允许自绘.
            
ColumnHeader ch = new ColumnHeader();
ch.Text = "标题列1";   //设置列标题
ch.Width = 120;       //设置列宽度
ch.TextAlign = HorizontalAlignment.Center;   //设置列的对齐方式,this.listView1.OwnerDraw = true有效.
this.listView1.Columns.Add(ch);              //将列头添加到ListView控件。

猜你喜欢

转载自blog.csdn.net/dd_zhouqian/article/details/89334021