简体   繁体   中英

How can I implement drag-and-drop to allow rearranging items in a ListView?

I would like to enable support for drag-and-drop in a ListView so that the user can rearrange the items, similar to what they can do in Windows Explorer.

Specifically, how do I enable the Drag event handler when I double-click on the ListView?

This is what I get after double-clicking on the ListView:

private void listView1(object sender, EventArgs e)

However, I want it to be:

private void listView(object sender, DragEventArgs e)

How can I do this?

I have tried many ways, such as:

  private void Form_Load(object sender, EventArgs e)
  {
      // Enable drag and drop for this form
      // (this can also be applied to any controls)
      this.AllowDrop = true;

      // Add event handlers for the drag & drop functionality
      this.DragEnter += new DragEventHandler(Form_DragEnter);
      this.DragDrop += new DragEventHandler(Form_DragDrop);
 }

But none of these seem to work.

You need to implement the DragEnter event and set the Effect property of the DragEventArgs. The DragEnter event is what allows things to be dropped into a control. After that the DragDrop event will fire when the mouse button is released.

Here is a version that will allow objects to be dropped into the a ListView:

    private void Form1_Load(object sender, EventArgs e)
    {
        listView1.AllowDrop = true;
        listView1.DragDrop += new DragEventHandler(listView1_DragDrop);
        listView1.DragEnter += new DragEventHandler(listView1_DragEnter);
    }

    void listView1_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

    void listView1_DragDrop(object sender, DragEventArgs e)
    {
        listView1.Items.Add(e.Data.ToString());
    }

No doubt your sample code was taken from : http://msdn.microsoft.com/en-us/library/system.windows.forms.control.allowdrop(v=vs.71).aspx

To answer your question: There is no built in functionality for dragging and dropping items within a ListView control. Even the MSDN documentation instructs you to implement your own code-behind for the various events in order to achieve this functionality (see the ListViewInsertionMark Class )

ObjectListView (an open source wrapper around .NET WinForms ListView) provides this ability without further work (plus lots of other nice features ). Have a look at the "Drag and Drop" tab of the demo.

使用中的 ObjectListView 的屏幕截图,显示了拖放式插入符号。

(source: codeproject.com )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM