ListView为用户显示带图标的项的列表,类似于windows资源管理器.
1.添加ImageList,一般添加两个
因为imageList是作为其他控件的资源,因此不在主窗口中显示.
然后点击imageList1,在属性的image列表中添加图片
imageList2类似
打开listview的属性窗口,将imageList1作为SmallImageList,imageList2作为LargeImageList
2.在listview属性窗口中添加项
将每个项配备之前的图片
3.在listview属性窗口中将view属性切换成detail类型,然后点击其中Column集合属性,添加4列
接着点开其中Items集合,对每个Item右边有个SubItem点进去后添加子项(为每列指定信息)
3.分组
进入listview属性窗口 点击group集合
点击Item集合,为每个项分配组
4.结果
当然也可以改变视图样式(只需改变listview属性窗口中view的枚举值),上面只是detail
5.拖拽
public partial class ListView : Form { public ListView() { InitializeComponent(); InitializeListView(); } private void InitializeListView() { listView1.ListViewItemSorter = new ListViewIndexComparer();//排序方式 listView1.InsertionMark.Color = Color.Red; listView1.AllowDrop = true;//允许拖拽 } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } private void listView1_ItemDrag(object sender, ItemDragEventArgs e) { listView1.DoDragDrop(e.Item, DragDropEffects.Move);//拖拽操作,效果移动 } private void listView1_DragEnter(object sender, DragEventArgs e) { e.Effect = e.AllowedEffect;//允许拖放 } private void listView1_DragOver(object sender, DragEventArgs e) { //获取鼠标坐标 Point point = listView1.PointToClient(new Point(e.X, e.Y)); //返回离鼠标最近的项目索引 int index = listView1.InsertionMark.NearestIndex(point); if (index > -1)//光标不在拖拽项目上 { //获取所选项的范围 Rectangle itemBounds = listView1.GetItemRect(index); //如果鼠标点在控件被插入项的右边 if (point.X > itemBounds.Left + (itemBounds.Width / 2)) { //在改项后面出现插入标记 listView1.InsertionMark.AppearsAfterItem = true; } else { listView1.InsertionMark.AppearsAfterItem = false; } } listView1.InsertionMark.Index = index; } private void listView1_DragLeave(object sender, EventArgs e) { //鼠标离开控件时候移除插入标记 listView1.InsertionMark.Index = -1; } private void listView1_DragDrop(object sender, DragEventArgs e) { //返回插入标记的索引值 int index = listView1.InsertionMark.Index; if (index == -1) return; if (listView1.InsertionMark.AppearsAfterItem) { index++; }//如果插入标记在项目的后面,则目标索引++ //获取拖拽项的数据 ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem)); listView1.Items.Insert(index, (ListViewItem)item.Clone());//插入副本 listView1.Items.Remove(item);//删除原文件 } private class ListViewIndexComparer : System.Collections.IComparer { public int Compare(object x, object y) { return ((ListViewItem)x).Index - ((ListViewItem)y).Index; } }
拖拽前
拖拽后
注:拖拽时候的InsertionMark没啥作用, 其次只有当项没有分组而且view的值是图标形式才能移动
另外对于 查找,使用FindItemWithText()方法,该方法有多个重载