有没有人在开发控件时找到了DesignMode问题的有用解决方案?
问题是,如果你嵌套控件,那么DesignMode只适用于第一级。第二个级别和更低级别的DesignMode将始终返回FALSE。
标准的技巧是查看正在运行的进程的名称,如果它是"DevEnv.EXE“,那么它一定是studio,因此DesignMode确实是真的。
这样做的问题是通过注册表和其他奇怪的部分查找ProcessName,最终结果是用户可能没有查看进程名称所需的权限。此外,这条奇怪的路线非常慢。因此,我们不得不堆积额外的hack来使用单例,如果在请求进程名称时抛出错误,则假定DesignMode为FALSE。
一种很好的、干净的方法来确定DesignMode是正确的。如果能让微软在内部将其修复到框架中就更好了!
发布于 2009-04-02 07:02:22
重新审视这个问题,我现在“发现”了5种不同的方法,它们如下:
System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString()
{
if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return "Present";
else
return "Not present";
}
public bool IsDesignerHosted
{
get
{
Control ctrl = this;
while(ctrl != null)
{
if((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly()
.Location.Contains("VisualStudio"))
}为了尝试理解所提出的三个解决方案,我创建了一个小测试解决方案--包含三个项目:
然后我将SubSubControl嵌入到SubControl中,然后每个都嵌入到TestApp.Form中。
此屏幕截图显示了运行时的结果。

此屏幕截图显示了在Visual Studio中打开窗体后的结果:

结论:似乎在没有反射的情况下,构造函数内唯一可靠的是LicenseUsage,而构造函数外唯一可靠的是'IsDesignedHosted‘(下面的BlueRaja )。
注:请参阅ToolmakerSteve下面的评论(我还没有测试过):“请注意,IsDesignerHosted answer已经更新为包含LicenseUsage...,所以现在测试可以简单地使用if (IsDesignerHosted)。另一种方法是test LicenseManager in constructor and cache the result。”
发布于 2010-04-23 02:19:20
来自this page
(__编辑2013,使用@hopla提供的方法,在构造函数中工作)
/// <summary>
/// The DesignMode property does not correctly tell you if
/// you are in design mode. IsDesignerHosted is a corrected
/// version of that property.
/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305
/// and http://stackoverflow.com/a/2693338/238419 )
/// </summary>
public bool IsDesignerHosted
{
get
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
return true;
Control ctrl = this;
while (ctrl != null)
{
if ((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}我已经向微软提交了a bug-report;我怀疑它会有什么用武之地,但无论如何都要投票支持它,因为这显然是一个bug (不管它是不是“故意的”)。
发布于 2008-12-06 21:29:10
你为什么不去看看LicenseManager.UsageMode呢。此属性的值可以是LicenseUsageMode.Runtime或LicenseUsageMode.Designtime。
如果您希望代码仅在运行时运行,请使用以下代码:
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
bla bla bla...
}https://stackoverflow.com/questions/34664
复制相似问题