Listview Item 拖动方法

使用Darg事件实现所属拖拽,要将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);
        }

 

posted @ 2017-04-12 15:07  这不是二哈  阅读(3388)  评论(0编辑  收藏  举报