先建立好ListView,ImageList,
然后编写一个比较类
在就是添加DragDrop事件了
具体实现看代码吧
-
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- InitializeListView();
- }
- // 初始化listView1.
- private void InitializeListView()
- {
- listView1.ListViewItemSorter = new ListViewIndexComparer();
- //初始化插入标记
- listView1.InsertionMark.Color = Color.Red;
- //
- listView1.AllowDrop = true;
- }
- // 当一个项目拖拽是启动拖拽操作
- 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);
- }
- // 对ListView里的各项根据索引进行排序
- private class ListViewIndexComparer : System.Collections.IComparer
- {
- public int Compare(object x, object y)
- {
- return ((ListViewItem)x).Index - ((ListViewItem)y).Index;
- }
- }
- }
- http://blog.csdn.net/lilongherolilong/article/details/6689109