.net - 具有嵌套控件的DesignMode

有没有人在开发控件时找到了解决DesignMode问题的有用方法?

问题是,如果嵌套控件,则DesignMode仅适用于第一级。 第二级和更低级别的DesignMode将始终返回FALSE。

标准的hack一直在查看正在运行的进程的名称,如果它是“DevEnv.EXE”那么它必须是studio,因此DesignMode真的是真的。

问题是寻找ProcessName通过注册表和其他奇怪的部分工作,最终结果是用户可能没有查看进程名称所需的权限。 另外这条奇怪的路线很慢。 所以我们不得不堆积额外的黑客来使用单例,如果在请求进程名称时抛出错误,则假设DesignMode为FALSE。

确定DesignMode的一个很好的干净方法是有序的。 实际上让微软在框架内部修复它会更好!

John Dyer asked 2019-09-10T13:43:01Z
12个解决方案
76 votes

重新审视这个问题,我现在已经'发现'了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"))
}

为了试图抓住提出的三个解决方案,我创建了一个小测试解决方案 - 有三个项目:

  • TestApp(winforms应用程序),
  • SubControl(dll)
  • SubSubControl(dll)

然后我将SubSubControl嵌入SubControl中,然后将其中一个嵌入TestApp.Form中。

此屏幕截图显示运行时的结果。Screenshot of running

此屏幕截图显示了在Visual Studio中打开表单的结果:

Screenshot of not running

结论:如果没有反射,在构造函数中唯一可靠的是LicenseUsage,并且在构造函数之外唯一可靠的是'IsDesignedHosted'(由BlueRaja在下面)

PS:请参阅下面的ToolmakerSteve评论(我还没有测试过):“请注意,IsDesignerHosted答案已更新为包含LicenseUsage ...,所以现在测试可以简单地为if(IsDesignerHosted)。另一种方法是在构造函数中测试LicenseManager 并缓存结果。“

Benjol answered 2019-09-10T13:44:21Z
30 votes

从这个页面:

([编辑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;
    }
}

我已经向微软提交了一份错误报告; 我怀疑它会去任何地方,但无论如何都要投票,因为这显然是一个错误(无论它是否是“按设计”)。

BlueRaja - Danny Pflughoeft answered 2019-09-10T13:45:00Z
29 votes

为什么不检查LicenseManager.UsageMode。此属性的值可以是LicenseUsageMode.Runtime或LicenseUsageMode.Designtime。

您是否希望代码仅在运行时运行,请使用以下代码:

if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
  bla bla bla...
}
hopla answered 2019-09-10T13:45:31Z
7 votes

这是我在表单中使用的方法:

    /// <summary>
    /// Gets a value indicating whether this instance is in design mode.
    /// </summary>
    /// <value>
    ///     <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.
    /// </value>
    protected bool IsDesignMode
    {
        get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }
    }

这样,即使DesignMode或LicenseManager属性中的任何一个失败,结果也是正确的。

husayt answered 2019-09-10T13:46:03Z
3 votes

我们成功使用此代码:

public static bool IsRealDesignerMode(this Control c)
{
  if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
    return true;
  else
  {
    Control ctrl = c;

    while (ctrl != null)
    {
      if (ctrl.Site != null && ctrl.Site.DesignMode)
        return true;
      ctrl = ctrl.Parent;
    }

    return System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";
  }
}
juFo answered 2019-09-10T13:46:30Z
3 votes

我的建议是优化@ blueraja-danny-pflughoeft的回复。此解决方案不是每次都计算结果,而是仅在第一次计算结果(对象无法将UsageMode从设计更改为运行时)

private bool? m_IsDesignerHosted = null; //contains information about design mode state
/// <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 https://stackoverflow.com/a/2693338/238419 )
/// </summary>
[Browsable(false)]
public bool IsDesignerHosted
{
    get
    {
        if (m_IsDesignerHosted.HasValue)
            return m_IsDesignerHosted.Value;
        else
        {
            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                m_IsDesignerHosted = true;
                return true;
            }
            Control ctrl = this;
            while (ctrl != null)
            {
                if ((ctrl.Site != null) && ctrl.Site.DesignMode)
                {
                    m_IsDesignerHosted = true;
                    return true;
                }
                ctrl = ctrl.Parent;
            }
            m_IsDesignerHosted = false;
            return false;
        }
    }
}
user2785562 answered 2019-09-10T13:46:55Z
3 votes

我使用LicenseManager方法,但缓存构造函数中的值以便在实例的整个生命周期中使用。

public MyUserControl()
{
    InitializeComponent();
    m_IsInDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
}

private bool m_IsInDesignMode = true;
public bool IsInDesignMode { get { return m_IsInDesignMode; } }

VB版:

Sub New()
    InitializeComponent()

    m_IsInDesignMode = (LicenseManager.UsageMode = LicenseUsageMode.Designtime)
End Sub

Private ReadOnly m_IsInDesignMode As Boolean = True
Public ReadOnly Property IsInDesignMode As Boolean
    Get
        Return m_IsInDesignMode
    End Get
End Property
Jonathan answered 2019-09-10T13:47:25Z
2 votes

我自己从来没有被这个抓住过,但是你不能从控件中走回Parent链,看看DesignMode是否设置在你的上方?

Will Dean answered 2019-09-10T13:47:49Z
2 votes

由于所有方法都不可靠(DesignMode,LicenseManager)或高效(进程,递归检查),我在程序级别使用public static bool Runtime { get; private set }并在Main()方法中明确设置它。

Boris B. answered 2019-09-10T13:48:14Z
1 votes

DesignMode是一个私有财产(据我所知)。 答案是提供一个暴露DesignMode道具的公共属性。 然后,您可以继续备份用户控件链,直到遇到非用户控件或处于设计模式的控件。 像这样......

  public bool RealDesignMode()
  {
     if (Parent is MyBaseUserControl)
     {
        return (DesignMode ? true : (MyBaseUserControl) Parent.RealDesignMode;
     }

     return DesignMode;
  }

所有UserControl都继承自MyBaseUserControl。 或者,您可以实现一个公开“RealDeisgnMode”的接口。

请注意,此代码不是现场代码,只是在袖口沉思。:)

Craig answered 2019-09-10T13:48:53Z
1 votes

我没有意识到你不能调用Parent.DesignMode(我也在C#中学到了一些关于'protected'的东西......)

这是一个反射版本:(我怀疑将designModeProperty设为静态字段可能会有性能优势)

static bool IsDesignMode(Control control)
{
    PropertyInfo designModeProperty = typeof(Component).
      GetProperty("DesignMode", BindingFlags.Instance | BindingFlags.NonPublic);

    while (designModeProperty != null && control != null)
    {
        if((bool)designModeProperty.GetValue(control, null))
        {
            return true;
        }
        control = control.Parent;
    }
    return false;
}
Will Dean answered 2019-09-10T13:49:27Z
0 votes

最近,当使用嵌套的UserControls时,我不得不在Visual Studio 2017中解决这个问题。 我结合上面和其他地方提到的几种方法,然后调整代码,直到我有一个合适的扩展方法,到目前为止可以接受。 它执行一系列检查,将结果存储在静态布尔变量中,因此每次检查最多只在运行时执行一次。 这个过程可能过度,但它会阻止代码在工作室中执行。 希望这有助于某人。

  public static class DesignTimeHelper
  {
    private static bool? _isAssemblyVisualStudio;
    private static bool? _isLicenseDesignTime;
    private static bool? _isProcessDevEnv;
    private static bool? _mIsDesignerHosted; 

    /// <summary>
    ///   Property <see cref="Form.DesignMode"/> does not correctly report if a nested <see cref="UserControl"/>
    ///   is in design mode.  InDesignMode is a corrected that property which .
    ///   (see https://connect.microsoft.com/VisualStudio/feedback/details/553305
    ///   and https://stackoverflow.com/a/2693338/238419 )
    /// </summary>
    public static bool InDesignMode(
      this Control userControl,
      string source = null)
      => IsLicenseDesignTime
         || IsProcessDevEnv
         || IsExecutingAssemblyVisualStudio
         || IsDesignerHosted(userControl);

    private static bool IsExecutingAssemblyVisualStudio
      => _isAssemblyVisualStudio
         ?? (_isAssemblyVisualStudio = Assembly
           .GetExecutingAssembly()
           .Location.Contains(value: "VisualStudio"))
         .Value;

    private static bool IsLicenseDesignTime
      => _isLicenseDesignTime
         ?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime)
         .Value;

    private static bool IsDesignerHosted(
      Control control)
    {
      if (_mIsDesignerHosted.HasValue)
        return _mIsDesignerHosted.Value;

      while (control != null)
      {
        if (control.Site?.DesignMode == true)
        {
          _mIsDesignerHosted = true;
          return true;
        }

        control = control.Parent;
      }

      _mIsDesignerHosted = false;
      return false;
    }

    private static bool IsProcessDevEnv
      => _isProcessDevEnv
         ?? (_isProcessDevEnv = Process.GetCurrentProcess()
                                  .ProcessName == "devenv")
         .Value;
  }
RB Davidson answered 2019-09-10T13:49:56Z
translate from https://stackoverflow.com:/questions/34664/designmode-with-nested-controls