2012-02-09 114 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; 
} 
相關問題