gtksharp TextView.PopulatePopup works to add handlers to existing menu items, but doesn't work to add new menu items

Viewed 46

I am trying to add items to the context menu of a TextView in GtkSharp (version 3.22.25.128). The context menu normally has the entries Cut/Copy/Paste/Delete/Separator/Select All/Insert Emoji. I am trying to add several more entries to the menu, starting with a separator.

To do this I am adding a handler to the PopulateMenu event, like so:

            _textBox.PopulatePopup += (object source, PopulatePopupArgs args) => {
            if (args.Popup is Menu menu)
            {
                (menu.Children[0] as MenuItem).Activated += 
                    (object src, EventArgs a) => {
                        Setting.SetRaw("This happened");
                    };
                foreach (var item in GetPopupMenuItems())
                {
                    menu.Add(item);
                }
            }
        };

An abbreviated version of GetPopupMenuItems() is:

    IEnumerable<MenuItem> GetPopupMenuItems()
    {
        yield return new SeparatorMenuItem();

        var importMenuItem = new MenuItem("Import single value from text file");
        importMenuItem.Activated += (object source, EventArgs args) => FileOperation(source as Window, true, false);
        yield return importMenuItem;
    }

The PopulatePopup handler is definitely being called; I can step through it in the debugger and see that at the end the Popup menu includes the items I'm trying to add. It's also certain that the handler and is having some effect, because the test handler I added to the first menu item is called when I select the Cut option in the right click menu. But although the behavior I add to an existing menu item is working, the new menu items I am adding are never shown.

Is there an additional step I have to do to get the items I am adding to the Menu's collection to show in the menu? I've implemented nested menus in the menubar for the same app, and I've never had to do anything but add items to the parent's collection.

If it makes a difference, I'm using Gtk# to make a cross-platform Windows/Linux app, and I'm observing this behavior on both platforms.

1 Answers

In PopulatePopup, you must set the Visible flag of items you are adding to "true" to get them to appear as expected.

This handler works as expected:

            _textBox.PopulatePopup += (object source, PopulatePopupArgs args) => {
            if (args.Popup is Menu menu)
            {
                foreach (var item in GetPopupMenuItems())
                {
                    item.Visible = true;
                    menu.Add(item);
                }
            }
        };
Related