Handling double click events on ListBox items in C#
双击列表框中的项目时,我正在尝试执行某些操作。 我已经找到了这样做的代码
1 2 3 4 5 6 7 8 9 | void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) { int index = this.listBox1.IndexFromPoint(e.Location); if (index != System.Windows.Forms.ListBox.NoMatches) { MessageBox.Show(index.ToString()); //do your stuff here } } |
但是,当我单击某个项目时,不会触发该事件。 如果我单击所有项目下面的列表框,则会触发该事件。
我将
有任何想法吗?
尝试使用带有MouseDown和DoubleClick事件的ListBox创建表单。据我所知,当DoubleClick不会触发时,唯一的情况是,如果在MouseDown内调用MessageBox.Show(...)。在其他情况下,它可以正常工作。
还有一件事,我不确定是否重要,但是无论如何。当然,您可以按以下方式获取项目的索引:
1 | int index = this.listBox1.IndexFromPoint(e.Location); |
但是这种方式也很好:
1 2 | if (listBox1.SelectedItem != null) ... |
这是我在MouseDoubleClick事件中使用的方法。
1 2 3 4 5 6 7 8 9 10 11 12 | private void YourMethodForDoubleClick(object sender, MouseButtonEventArgs e) { Type sourceType = e.OriginalSource.GetType(); if (sourceType != typeof(System.Windows.Controls.TextBlock) && sourceType != typeof(System.Windows.Controls.Border)) return; //if you get here, it's one of the list items. DoStuff(); ... } |
感谢您的所有答复。现在可以使用了。如26071986所述,我通过检查e.Clicks是否为1在MouseDown处理程序中处理双击来解决该问题。如果是,则调用DoDragDrop,否则,我将调用处理双击的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | private void MouseDown_handler(object sender, MouseEventArgs e) { var listBox = (ListBox) sender; if (e.Clicks != 1) { DoubleClick_handler(listBox1.SelectedItem); return; } var pt = new Point(e.X, e.Y); int index = listBox.IndexFromPoint(pt); // Starts a drag-and-drop operation with that item. if (index >= 0) { var item = (listBox.Items[index] as MyObject).CommaDelimitedString(); listBox.DoDragDrop(item, DragDropEffects.Copy | DragDropEffects.Move); } } |
对我有用,所以我认为列表中的项目可能有一些问题(自定义?拦截事件?),或者事件未正确连接。
例如,尝试以下操作(完整的Form1.cs):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class MyObject { public MyObject(string someValue) { SomeValue = someValue; } protected string SomeValue { get; set; } public override string ToString() { return SomeValue; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); var list = new List<MyObject> { new MyObject("Item one"), new MyObject("Item two") }; listBox1.DataSource = list; } private void listBox1_DoubleClick(object sender, EventArgs e) { Debug.WriteLine("DoubleClick event fired on ListBox"); } } } |
使用包含以下内容的设计器源文件(Form1.Designer.cs):
1 2 3 4 |
作为测试,通过模板创建一个新的Forms基础应用程序,然后仅添加ListBox并定义一个类MyObject。查看是否观察到相同或不同的行为。
约翰:那就行了。但是我发现该事件没有被触发,因为我也在处理MouseDown事件。我试图删除MouseDown处理,然后它起作用。是否有处理这些事件的流畅方法?如果没有,我只需要找到其他方法来捕获MouseDown事件中的双击。