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);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM