Tip: solve the problem that the DesignMode cannot correctly reflect whether it is in the design mode.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.