I found this answer on Stackoverflow: DesignMode with NestedControls.
The best answer stated that, if you don't want to use reflection, and you want to check in the constructor whether you are in DesignMode, you should use something like:
bool inDesignMode = System.ComponentModel.LicenseManager.UsageMode == LicenseUsageMode.Designtime;
To test this, I created a simple usercontrol with three Labels:
public MyUserControl()
{
InitializeComponent();
this.label1.Text = String.Format("Construction: DesignMode: {0}", this.DesignMode);
bool inDesignMode = System.ComponentModel.LicenseManager.UsageMode == LicenseUsageMode.Designtime;
this.label2.Text = String.Format("Construction: LicenseManager: {0}", inDesignMode);
}
private void Onload(object sender, EventArgs e)
{
this.label3.Text = String.Format("OnLoadDesignMode: {0}", this.DesignMode);
}
I also created a Form with this Usercontrol on it. If I use the designer to show the Form, I see the following:
Conclusion: in the constructor you can't use DesignMode. However,you can use the LicenseManager
However, if I open the usercontrol in the designer, it seems like the constructor isn't even used!
So now I am a bit confused.
However, if I open the usercontrol in the designer, it seems like the constructor isn't even used! So now I am a bit confused.
The designer doesn't call the constructor of the root component that you are designing. Instead, it calls the constructor of the base class of the root component, then parse the designer-generated code of your root component, create child components and set properties and add them to the root and and load the designer.
Now it should be clear what is happening here:
When you are designing MyUserControl:UserControl
, the constructor of UserControl
will be called. (Constructor of MyUserControl
is useless here.)
When you are designing Form1: Form
which has an instance of MyUserControl
on it, constructor of Form
will be called, Form1.Designer.cs
will be parsed and since there is an instance of MyUserControl
, constructor of MyUserControl
will run and an instance of the control will be added to design surface.
You can find an interesting example in this post or the other which shows how designer parses and loads a form (which has some serious syntax problems in designer code).