2012-02-09 25 views
18

öğelerini seçmek için tıklatınız Sağ tıklayıp içerik menüsüne sahip olarak çeşitli eylemleri gerçekleştirebileceğiniz öğelerin bir listesini yapmaya çalışıyorum. Bunu tamamladım, sorun değil.Sağ ListBox

Ancak, bir öğeyi sağ tıklattığınızda, seçili öğeyi bırakmak yerine, öğenin seçilmesi için farenin üzerine gelmesini istiyorum.

Bu ve diğer ilgili soruları araştırdım ve indexFromPoint'i (araştırmamda bulduğum) kullanmayı denedim, ancak bir öğeye sağ tıklarsanız her zaman seçili öğeyi temizler ve bağlam menüsünü, seçmiş olduğum gibi göstermez, böylece seçili bir öğe yoksa görünmez. İşte

Şu anda kullanarak kodudur:

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

Bu görünüyor System.Windows.Forms.ListBox'taki bir hata gibi, Microsoft'a bildirmeliyiz. içerik menüsü zaten liste kutusu sınırlanmış ise –

cevap

31

Kol ListBox.MouseDown ve orada öğeyi seçin. Şunun gibi:

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

, sadece kullanın: özel geçersiz listBoxItems_MouseDown (object sender, MouseEventArgs e) { listBoxItems.SelectedIndex = listBoxItems.IndexFromPoint (e.X, e.Y); } –

5

bu bir çalışıyor ...

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

Sadece bu satır listesinin yerini değiştirBox.Items [index]; .SelectedIndex = index ile; ve bu mükemmel çalışıyor. –

+0

Tıklama olayının doğru düğmeyi veya ortadaki düğmeyi yakalamadığı görülüyor. Onları yakalamak için MouseUp kullanmak zorundasın .. – MattClimbs

0

da sonra tüm liste üzerinde bir MouseRightButtonUp olayı ayarlayarak aynı davranışı elde edebilir:

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; 
}