实际上调整一个ListView
并不比主人画它容易。这是一个例子,表明它实际上是多么简单。
您只需编写一个事件的脚本(DrawItem
)然后你就完成了。
这段代码假设:
- LV 的视图设置为列表
- 您已将合适的 ImageList 添加到表单中
- 您已将 LV 的 OwnerDraw 设置为 true
- 您已添加两列来保存两个标签中显示的文本
- 您已使第一列足够宽以容纳绘制的全部内容
- 您已将 LV 的 FontSize 设置为与图像的高度一样大(例如 32)
- 将适当的 ImageIndex 值分配给 LV 的 Items
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
Point point0 = new Point(e.Bounds.Left, e.Bounds.Top);
Point point1 = new Point(imageList1.ImageSize.Width + 10, e.Bounds.Top + 5);
Point point2 = new Point(imageList1.ImageSize.Width + 10, e.Bounds.Top + 25);
Size size = new Size(listView1.ClientRectangle.Width, e.Bounds.Height);
Rectangle R = new Rectangle(point0, size);
Font F1 = new Font(listView1.Font.FontFamily, 11f, FontStyle.Bold);
Font F2 = new Font(listView1.Font.FontFamily, 10f);
if (e.Item.Focused) e.Graphics.FillRectangle(Brushes.LightBlue, R);
else if (e.ItemIndex % 2 == 1) e.Graphics.FillRectangle(Brushes.GhostWhite, R);
e.Graphics.DrawImage(imageList1.Images[e.Item.ImageIndex], point0 );
e.Graphics.DrawString(e.Item.Text, F1, Brushes.Black, point1);
e.Graphics.DrawString(e.Item.SubItems[1].Text, F2, Brushes.Black, point2);
F1.Dispose(); F2.Dispose();
}
请注意,我已经硬编码了一些颜色来绘制每隔一行以及焦点项目。这些颜色确实应该使用各自的系统颜色。我想到了这些:
SolidBrush brush0 = new SolidBrush(SystemColors.ControlLight);
SolidBrush brush1 = new SolidBrush(SystemColors.Highlight);
我使用的是分配给 LV 的字体,但大小适中。显然,或多或少的任何东西,尤其是各种偏移量,都可以根据您的喜好进行配置。但使用的颜色System.Colors
集合是与用户的 Windows 主题保持一致的好方法。