源代码 http://download.csdn.net/detail/songconglai/5190885
建个winform工程 添加 listview 控件 设置 allowDrop 为true ,添加DragDrop,DragEnter,DragLeave,DragOver事件
public Form1()
{
InitializeComponent();
listView1.ListViewItemSorter = new ListViewIndexComparer();
}
private void button1_Click(object sender, EventArgs e)
{
}
//启动拖拽,设置拖拽的数据和效果。
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
listView1.DoDragDrop(e.Item, DragDropEffects.Move);
}
//拖拽进入ListView,判断拖拽的数据格式,并设置拖拽的效果。
private void listView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.AllowedEffect;
//e.Effect = DragDropEffects.Move;
}
//拖动经过ListView时,设置拖动的效果,显示拖放位置线
private void listView1_DragOver(object sender, DragEventArgs e)
{
Point ptScreen = new Point(e.X, e.Y);
Point pt = listView1.PointToClient(ptScreen);
ListViewItem item = listView1.GetItemAt(pt.X, pt.Y);
int targetIndex = listView1.InsertionMark.NearestIndex(pt);
if (targetIndex >-1)
{
Rectangle itemBounds = listView1.GetItemRect(targetIndex);
if (pt.X > itemBounds.Left + (itemBounds.Width / 2))
{
listView1.InsertionMark.AppearsAfterItem = true;
}
else {
listView1.InsertionMark.AppearsAfterItem = false;
}
}
listView1.InsertionMark.Index = targetIndex;
//if (item != null)
// item.Checked = true;
}
//拖拽释放,移动行
private void listView1_DragDrop(object sender, DragEventArgs e)
{
int targetIndex = listView1.InsertionMark.Index;
if (targetIndex == -1)
{
return;
}
if (listView1.InsertionMark.AppearsAfterItem)
{
targetIndex++;
}
ListViewItem draggedItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
//Point ptScreen = new Point(e.X, e.Y);
//Point pt = listView1.PointToClient(ptScreen);
//ListViewItem targetItem = listView1.GetItemAt(pt.X, pt.Y);//拖动的项将放置于该项之前
//if (null == targetItem || targetItem == draggedItem)
// return;
// NeedForFix: 项实际已经交换,但是显示没有交换
listView1.BeginUpdate();
listView1.Items.Insert(targetIndex, (ListViewItem)draggedItem.Clone());
listView1.Items.Remove(draggedItem);
listView1.EndUpdate();
}
private void listView1_DragLeave(object sender, EventArgs e)
{
listView1.InsertionMark.Index = -1;
}
private class ListViewIndexComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return ((ListViewItem)x).Index - ((ListViewItem)y).Index;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}