我想制作一个包含许多类似项目的列表视图(详细)。为了更具可读性,我希望每个 listview.items.count % 2 == 0 行都作为 backolor.lightgray。
我已经按照本网站的说明制作了一个 listviewColumnSorter:http: //support.microsoft.com/kb/319401
经过一些修改,使数据看起来与我需要使用的数据“相似”,我的代码如下:
public partial class Form1 : Form
{
private ListViewColumnSorter lvwColumnSorter;
public Form1()
{
InitializeComponent();
lvwColumnSorter = new ListViewColumnSorter();
this.listView1.ListViewItemSorter = lvwColumnSorter;
}
private void Form1_Load(object sender, EventArgs e)
{
ColumnHeader columnheader; // Used for creating column headers.
ListViewItem listviewitem; // Used for creating listview items.
// Ensure that the view is set to show details.
listView1.View = View.Details;
for (int i = 0; i < 10; i++)
{
listviewitem = new ListViewItem("item" + i.ToString());
if (listView1.Items.Count % 2 == 0)
{
listviewitem.BackColor = Color.LightGray;
listviewitem.SubItems.Add("xxx");
}
else
listviewitem.SubItems.Add("yyy");
this.listView1.Items.Add(listviewitem);
}
// Create some column headers for the data.
columnheader = new ColumnHeader();
columnheader.Text = "First Name";
this.listView1.Columns.Add(columnheader);
columnheader = new ColumnHeader();
columnheader.Text = "Last Name";
this.listView1.Columns.Add(columnheader);
// Loop through and size each column header to fit the column header text.
foreach (ColumnHeader ch in this.listView1.Columns)
{
ch.Width = -2;
}
}
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == SortOrder.Ascending)
{
lvwColumnSorter.Order = SortOrder.Descending;
}
else
{
lvwColumnSorter.Order = SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
this.listView1.Sort();
}
}
(+ 来自 msdn 站点的 ListViewColumnsSorter 类。)
如果您对第二列(姓氏)进行排序,您会看到,所有 xxx 列都是灰色的,yyy 是白色的,并且由于颜色似乎与数据绑定,我最初的想法是让每一列都变成灰色,现在毁了。
我可以以某种方式保持排序功能,并且总是每隔一行灰色,独立于数据吗?
图片:
所以要非常清楚,在任何列中排序后,我想每隔一行保留一次浅灰色。如何做到这一点?
(.net 4)