简体   繁体   中英

WPF contextMenu click issue

A ListBox and a ContextMenu are created dynamicaly. The ListBox has some items. How do I know the ListBoxItem Text that right mouse button clicked on?

private void Init2()
{ 
    ContextMenu contextMenu = new ContextMenu();

    MenuItem menuItemOpen = new MenuItem();
    menuItemOpen.Click += new RoutedEventHandler(menuItemOpen_Click);
    contextMenu.Items.Add(menuItemOpen);
    listBox1.ContextMenu = contextMenu;
}
void menuItemOpen_Click(object sender, RoutedEventArgs e)
{
    //How do I know the listItem text that  right mouse button clicked on?
}

When you right click, you actually also select. So that means you can just do:

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        string selectedListBoxItemText = ((ListBoxItem)listBox1.SelectedItem).Content.ToString());

        // do your thing
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM