在 2 个列表框之间拖放 [英] Drag and Drop between 2 list boxes

查看:16
本文介绍了在 2 个列表框之间拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 2 个列表框之间实现拖放,到目前为止我看到的所有示例都不是很好闻.

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?

推荐答案

这是一个示例表单.开始使用新的 WF 项目并在表单上放置两个列表框.使代码如下所示:

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 个列表框之间拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆