views:

165

answers:

5

Hey guys,

I'm trying to sho a contextmenu on right-click on 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.

A: 

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?

Werewolve
the events don't work when clicking on a listboxitem, only when u click on white space...I want to right-click on an item in the list, and showing a context menu.
djerry
A: 

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.

Wim Haanstra
euhm, why not just use MouseRightButtonDown instead of checking which button is clicked...?btw, i'm working in wpf, and it seems it doesn't have indexfrompoint
djerry
because you doesn't say that you use WPF. Maybe there is something different.
Werewolve
+1  A: 

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

Werewolve
Nice, almost the same code :D, except I am not sure how this works in WPF.
Wim Haanstra
In your XAML, you have to define the MouseDown or OrMouseDown event. It's pretty much like non-WPF code.
David Brunelle
it's dynamic, cannot put an event to a listboxitem or whatever, it is depending on the items, so putting it in XAML will not work
djerry
A: 

This will answer your question I think:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/2c8f00ca-9c7d-4237-b2cf-f60911a008a9

Wim Haanstra
+1  A: 

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.