Add a click event to a listbox filled with objects in code
I'm trying to sho a contextmenu on right-click 开发者_如何学Pythonon an item in a listbox. So i'm binding a list of "Users" to my listbox. Then i'm a bit lost. I thought i could foreach the list and add a mouserightdown event on the listboxitems, but i can't figure out how.
Is this a good way, or does anyone know a better way of accomplishing what i want.
Thanks in advance.
You can do 2 things that may solve the problem you are experiencing :
1) If you use usercontrols to fill your listbox, you can add click events to it.
2) If you add a contextmenu to your listbox, right-clicking an item will automatically open the contextmenu, so you don't have to add a click event to it.
This will work:
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Point p = new Point(e.X, e.Y);
listBox1.SelectedIndex = listBox1.IndexFromPoint(p);
contextMenuStrip1.Show();
}
}
Edit: a bit too late sry ;)
maybe you can get in the Mousdown Event from the Listbox, witch Item is selected. Or do you do the right click without have a item selected?
Been a while since I did this, but if I remember correctly:
- You should trigger the event on right-mouse-down
- Figure out the location of the cursor at that time
- Ask the listbox, which item sits at those coordinates.
The listbox does have a method for that I think...
Edit: Here, have some code:
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != System.Windows.Forms.MouseButtons.Right)
return;
int index = listBox1.IndexFromPoint(e.X, e.Y);
MessageBox.Show(listBox1.Items[index].ToString());
}
Obviously, you need to add some error checking, if there is an item at that point etc.
This will answer your question I think:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/2c8f00ca-9c7d-4237-b2cf-f60911a008a9
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Point p = new Point(e.X, e.Y);
listBox1.SelectedIndex = listBox1.IndexFromPoint(p);
contextMenuStrip1.Show();
}
}
精彩评论