What is the correct way to dynamically select menu items for a context menu in WinForms?

I am trying to create a context menu for a control associated with a main menu item. There are two fixed menu items that are always there, and an arbitrary number of additional menu items that can be on the menu.

I tried to solve the problem by storing the class level link for fixed menu items and a list of dynamic menu items. I handle menu events by Openingclearing the current list of items and then adding the appropriate items to the menu. This works great for the main menu, but the context menu behaves strangely.

The main problem is that by the time the Openingmenu was created, it had already determined which items would be displayed. This form demonstrates:

using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class DemoForm : Form
    {
        private List _items;

        public DemoForm()
        {
            var contextMenu = new ContextMenuStrip();
            contextMenu.Opening += contextMenu_Opening;

            _items = new List();
            _items.Add(new ToolStripMenuItem("item 1"));
            _items.Add(new ToolStripMenuItem("item 2"));


            this.ContextMenuStrip = contextMenu;
        }

        void contextMenu_Opening(object sender, CancelEventArgs e)
        {
            var menu = sender as ContextMenuStrip;

            if (menu != null)
            {
                foreach (var item in _items)
                {
                    menu.Items.Add(item);
                }
            }
        }
    }
}

When you right-click a form for the first time, nothing is displayed. The second time the menu is displayed as expected. Is there any other event when I can update items? Bad practice for dynamically selecting menu items?

(: , , ​​, , , , . "" " , , . .)

+3
1

MouseDown . , .

+2

Source: https://habr.com/ru/post/1697221/


All Articles