最近有开发需求涉及的listview 的listviewitem的排序的问题,找了些资料都是断断序序的,把我的实现方法总结一下,
主要实现代码如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private ListViewItem itemDraged=null;//定义拖动的item
private ListViewItem itemSelected = null;//定义拖动到位置的item
bool isdrag = false;//是否拖动状态
//ItemMouseHover方法实现鼠标拖动到某个元素上时更改该元素的被选中状态
private void lsvFilms_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
{
itemSelected = e.Item;
if (isdrag)
{
e.Item.Selected = true;
}
else
{
e.Item.Selected = false;
}
}
//ItemDrag获取被拖动的item
private void lsvFilms_ItemDrag(object sender, ItemDragEventArgs e)
{
itemDraged = (ListViewItem)e.Item;
this.Cursor = Cursors.Hand;
isdrag = true;
}
//MouseUp当拖动放开鼠标时,进行位置调整操作
private void lsvFilms_MouseUp(object sender, MouseEventArgs e)
{
isdrag = false;
if ((itemSelected != null) && (itemDraged != null))
{
if (itemDraged.Index != itemSelected.Index)
{
this.lsvFilms.Items.RemoveAt(itemDraged.Index);
this.lsvFilms.Items.Insert(itemSelected.Index, itemDraged);
itemDraged = null;
itemSelected = null;
}
}
this.Cursor = Cursors.Default;
}
其实就是几个简单的逻辑顺序,如果朋友有更好的方法,希望能与你交流。谢谢!