Drag and Drop between 2 list boxes

萝らか妹 提交于 2019-12-30 07:22:11

问题


Trying to implement drag and drop between 2 listboxes and all examples I've seen so far don't really smell good.

Can someone point me to or show me a good implementation?


回答1:


Here's a sample form. Get started with a new WF project and drop two list boxes on the form. Make the code look like this:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      listBox1.Items.AddRange(new object[] { "one", "two", "three" });
      listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
      listBox1.MouseMove += new MouseEventHandler(listBox1_MouseMove);
      listBox2.AllowDrop = true;
      listBox2.DragEnter += new DragEventHandler(listBox2_DragEnter);
      listBox2.DragDrop += new DragEventHandler(listBox2_DragDrop);
    }

    private Point mDownPos;
    void listBox1_MouseDown(object sender, MouseEventArgs e) {
      mDownPos = e.Location;
    }
    void listBox1_MouseMove(object sender, MouseEventArgs e) {
      if (e.Button != MouseButtons.Left) return;
      int index = listBox1.IndexFromPoint(e.Location);
      if (index < 0) return;
      if (Math.Abs(e.X - mDownPos.X) >= SystemInformation.DragSize.Width ||
          Math.Abs(e.Y - mDownPos.Y) >= SystemInformation.DragSize.Height)
        DoDragDrop(new DragObject(listBox1, listBox1.Items[index]), DragDropEffects.Move);
    }

    void listBox2_DragEnter(object sender, DragEventArgs e) {
      DragObject obj = e.Data.GetData(typeof(DragObject)) as DragObject;
      if (obj != null && obj.source != listBox2) e.Effect = e.AllowedEffect;
    }
    void listBox2_DragDrop(object sender, DragEventArgs e) {
      DragObject obj = e.Data.GetData(typeof(DragObject)) as DragObject;
      listBox2.Items.Add(obj.item);
      obj.source.Items.Remove(obj.item);
    }

    private class DragObject {
      public ListBox source;
      public object item;
      public DragObject(ListBox box, object data) { source = box; item = data; }
    }
  }



回答2:


the proper way to do a drag-drop control in .net is by running code in the 2nd control's DragDrop event handler.

It may "smell" weird, but this is how it works in .NET.




回答3:


Google gave this: http://www.codeproject.com/KB/dotnet/csdragndrop01.aspx

It seems a pretty reasonable tutorial. If it smells bad, I think that's more to do with the API for drag and drop being awkward to use rather than the tutorial itself being poor.



来源:https://stackoverflow.com/questions/1822497/drag-and-drop-between-2-list-boxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!