Question

I have a problem, what designer doesn't add inherited ContextMenuStrip to the components. Here is how to reproduce the problem:

  1. Create new project (windows forms application).
  2. Add to the form ContextMenuStrip via designer, it will generate this:

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
        ...
    }
    
  3. Create MyContextMenuStrip class:

    public class MyContextMenuStrip : ContextMenuStrip
    {
    }
    
  4. Compile and add to the form MyContextMenuStrip via designer, it will generate this:

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
        this.myContextMenuStrip1 = new WindowsFormsApplication1.MyContextMenuStrip();
        ...
    }
    

WTF? Why it's not adding MyContextMenuStrip to the components???

And I need menu to be present in components for my localization manager (to automatically translate menus). Do I forgot some attribute, interface or override??

Was it helpful?

Solution

Visual Studio isn't initializing your MyContextMenuStrip with a Container because your control doesn't have a constructor that accepts a Container as a parameter.

Create a constructor in your MyContextMenuStrip that takes a System.ComponentModel.IContainer and then pass this parameter to your control's base class using the base keyword:

class MyContextMenuStrip : ContextMenuStrip
{
    public MyContextMenuStrip(System.ComponentModel.IContainer c) : base(c) { }
}

After doing this you'll find that when you add your MyContextMenuStrip to a Form using the designer, VS will generate the code you want in your Form's InitializeComponent method:

this.myContextMenuStrip1 = new WindowsFormsApplication1.MyContextMenuStrip(this.components);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top