简体   繁体   中英

ContextMenuStrip assign dynammically to dropdownbutton items C# WINFORM

I am building a web browser in WINFORMS. I have a dropdown button in a toolstrip. The items of dropdown are added dynamically from a XML file at runtime. The dropdown button is used for viewing bookmars. I have a contextmenu with add and delete bookmark options. I see no contextmenuproperty for dropdownbutton items. I need to display the contextmenu on right click for each item in the drop-down button. I couldn't even find mouseclick event for items. Therefore no e.location

//I have got these events do far (just handles the click)
    private void bookmarksDropDownButton2_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
            {
                tabControlBrowser.SelectedTab = tabControlBrowser.TabPages[tabControlBrowser.TabPages.Count - 1];
                getCurrentWebBrowser().Navigate(dictionary[e.ClickedItem.Text]);
                AddressComboBox1.Text = dictionary[e.ClickedItem.Text];
            }

I hooked up the events in this way in my code

    foreach (ToolStripItem item in bookmarksDropDownButton2.DropDownItems)
            {
                item.MouseDown += new MouseEventHandler(item_MouseDown);
            }
    private void item_MouseDown(object sender, MouseEventArgs e)
        {
              BOOKcontextMenuStrip1.Show(e.Location);
              //this one pop's out the menu at the uppermost corner of the window.
        }

在此处输入图片说明

You can unfortunately not hook up a ContextMenu to individual items in a ToolStrip . What you need to do is to set the context menu when you are right-clicking the DropDownButton, on its MouseDown event (check for which mouse-button) to the toolstrip itself.

  • Or in this case:

You will need instead to dynamically add a handler for the MouseDown event for each of your items so you can get the actual item selected (hovered). When an item is right-clicked you assign the context-menu to the tool-strip itself (you can now store the ID of the item clicked in f.ex. the context menu's Tag property).

On the ContextMenu's Closed event you then remove the menu from toolstrip ( .ContextMenuStrip=null ).

I'm sorry I don't have a C# example right now. Let me know if it's clear enough or not, in which case I'll try to add an example.

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