2012-02-09 107 views
18

我正在试图制作一个项目列表,您可以通过右键单击并出现上下文菜单来执行多项操作。我已经完成了,没有任何问题。右键单击以选择列表框中的项目

但我想这样做,所以当你右键点击一个项目,而不是离开当前选择的项目,选择鼠标结束的项目。

我已经研究了这个和其他相关的问题,我试图使用indexFromPoint(我通过我的研究发现),但每当我右键点击一个项目,它总是只清除选定的项目,并没有显示上下文菜单,因为我有它的设置,所以如果没有选定的项目,它不会出现。

这是我目前使用的代码:

ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y); 
+0

这看起来像System.Windows.Forms.ListBox中的错误,我们应该将其报告给Microsoft。 – 2015-08-03 10:53:57

回答

31

手柄ListBox.MouseDown,并在那里选择项目。就像这样:

private void listBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y); 
} 
+4

如果上下文菜单已经绑定到列表框,只需使用: private void listBoxItems_MouseDown(object sender,MouseEventArgs e) { listBoxItems.SelectedIndex = listBoxItems.IndexFromPoint(e.X,e.Y); } – 2013-01-13 14:17:32

5

这一项工作...

this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick); 

private void List_RightClick(object sender, MouseEventArgs e) 
{ 

    if (e.Button == MouseButtons.Right) 
    { 
     int index = this.listBox.IndexFromPoint(e.Location); 
     if (index != ListBox.NoMatches) 
     { 
      listBox.Items[index]; 
     } 
    } 

} 
+0

刚刚取代了这一行listBox.Items [index];与.SelectedIndex = index;这完美地工作。 – 2014-12-24 19:35:42

+0

奇怪的是,单击事件似乎没有捕获到正确的按钮或中间按钮。必须使用MouseUp捕捉它们.. – MattClimbs 2015-11-01 01:57:27

0

也可以通过对整个列表框中设置的MouseRightButtonUp事件再拿到相同的行为:

private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e) 
{ 
    // If have selected an item via left click, then do a right click, need to disable that initial selection 
    AccountItemsT33.SelectedIndex = -1; 
    VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true; 
} 
相关问题