Visual Form editor provided by VS is very useful, but it also has some annoying problems, such:
- You cannot edit the Control/Form inherited from the virtual base class or fan base class;
- Sometimes the attribute DesignMode does not correctly reflect whether it is in the design mode. Specifically, it is the custom control A nested in custom control B, if B is placed on another control/form, the DesignMode attribute of A cannot correctly reflect its environment;
And so on...
For the former, there are indeed some ways to do it, but in general, after using these methods, you will only hate Visual Studio (if you really want to know, okay, first, write a non-fan non-virtual base class that inherits from the original base class, and then the Child class can enter the design mode based on this class); the latter, there is indeed a way to make you forget these unhappiness.
Code:
Class VSDesignerFix
{
// Returns True, if specified control or one of their parent control is in design mode.
Public static bool IsInDesignMode (Control control)
{
If (control = null)
{
Throw new ArgumentNullException ("control ");
}
Bool result = false; // return value
Control ctl = control; // checked control for design mode
Do
{
ISite site = ctl. Site; // get the site object, which is set by designer
If (site! = Null)
{
Result = site. DesignMode; // check for design mode
If (result) {break;} // if control is in design mode then loop ends
}
} While (ctl = ctl. Parent )! = Null); // track the parent control
Return result;
}
}
Usage:
Public class MyControl: Control
{
Public MyControl ()
{
}
Protected override void OnLoad (EventArgs e)
{
Base. OnLoad (e );
If (! VSDesignerFix. IsInDesignMode (this ))
{
// Enter the code that does not need to be run in design mode.
}
}
}
God belongs to God, and Caesar belongs to Caesar. This Tip is attributed to Jakub Mller.