【发布时间】:2019-06-23 02:47:00
【问题描述】:
我正在尝试在 Windows 窗体中的 ListBox 之间拖放多个项目。我遇到的问题是,如果我选择多个按住 Shift 键的项目并尝试在不释放键的情况下拖放它,我会收到错误消息。实际上 SelectedIndices 和 SelectedItems 只显示 1 个项目,即我首先单击的那个,即使多个项目在 ListBox 中突出显示。
我正在使用 SelectionMode = MultiExtended
void ZListBox_MouseMove(object sender, MouseEventArgs e)
{
if (isDraggingPoint.HasValue && e.Button == MouseButtons.Left && SelectedIndex >= 0)
{
var pointToClient = PointToClient(MousePosition);
if (isDraggingPoint.Value.Y != pointToClient.Y)
{
lastIndexItemOver = -1;
isDraggingPoint = null;
var dropResult = DoDragDrop(SelectedItems, DragDropEffects.Copy);
}
}
}
似乎如果我在执行“DoDragDrop”之前不释放鼠标左键,则不会选择项目,并且如果我尝试从另一个 ListBox 获取 SelectedIndices,则计数是“选定的项目”,但是当我尝试浏览列表时,我得到一个 IndexOutOfRangeException。
有什么解决办法吗?
重现问题的示例代码: (重现: 1- 选择一个项目 2- 按住 shift 并单击另一个项目,而不是释放 shift 和鼠标按钮,拖动此项目(如果您在“if”中有断点,您将在 SelectedItems 上看到只有 1 个项目))
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
var someList = new List<ListItemsTest>();
someList.Add(new ListItemsTest() { ID = 1, Name = "Name 1" });
someList.Add(new ListItemsTest() { ID = 2, Name = "Name 2" });
someList.Add(new ListItemsTest() { ID = 3, Name = "Name 3" });
someList.Add(new ListItemsTest() { ID = 4, Name = "Name 4" });
someList.Add(new ListItemsTest() { ID = 5, Name = "Name 5" });
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";
listBox1.DataSource = someList;
listBox1.SelectionMode = SelectionMode.MultiExtended;
listBox1.MouseMove += ListBox1_MouseMove;
listBox1.AllowDrop = true;
}
void ListBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && listBox1.SelectedIndex >= 0)
{
var dropResult = DoDragDrop(listBox1.SelectedItems, DragDropEffects.Copy);
}
}
public class ListItemsTest
{
public int ID { get; set; }
public string Name { get; set; }
}
}
【问题讨论】:
-
您从哪里获得 SelectedIndex 和 SelectedItems 值?哪一行抛出错误?记录所有这些。
-
@LarsTech 当我在 MouseMove 上获得 SelectedItems 时,只有 1 个项目。当我在另一个 ListBox 中并尝试获取 ListBox1.SelectedItems 时出现错误
-
问题是,在我开始拖放之前,SelectedItems 是错误的,如果我不释放鼠标按钮,它永远不会选择项目
-
我添加了一张图片
-
我编辑了已经存在的代码
标签: c# winforms drag-and-drop listbox