Introduction
This is a fast, reliable method to determine if you are currently in Design Mode.
Background
Background is the usual for this one - I needed to do certain things with my custom control in design mode. Noting fairly quickly that the DesignMode
property was not reliable, I did the usual searches, and came up with a number of methods (including Mika Wendelius' [^] article here[^]). The possibilities were:
It also should be noted that once a module if found to be in design mode or not, the mode does not change. As such, once the mode has been determined, any subsequent calls should just return the previous result, rather than going through the process all over again.
The final result I came up with is:
static class DesignModeExtension {
static bool? _isinDesignMode = null;
public static bool IsInDesignMode(this Control control) {
if (!_isinDesignMode.HasValue) {
_isinDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
while (!_isinDesignMode.Value && control != null) {
_isinDesignMode = control.Site?.DesignMode ?? false;
control = control.Parent;
}
}
return _isinDesignMode.Value;
}
}
Firstly, I check whether the mode has already been determined. If it hasn't, I proceed to determine it.
The determination starts with the fastest method, albeit unreliable. However, it is only the "false
" return value that is unreliable. If this test returns true
, then there is no need to traverse the controls to see if they are in design mode. Finally, if needed, I traverse the control's parents until I either find one that confirms I am in design mode, or I reach the end, in which case I can be certain that the application is not in design mode. I then save the final result before returning it to the caller.
Using the Code
The attached source is not in any project - it is simply a .cs file containing the definition. To install it, simply add this file to your project.
Using the extension is as simple as if (this.IsInDesignMode())
. This can be called from anywhere within a control's scope.