假设我有一个自定义WinForms控件:

public class MyBaseControl : Control
{
     ...
}


扩展如下:

public class MyControl : MyBaseControl
{
     ...
}


通过检查this.DesignMode属性标志,很容易确定控件是否在视觉上进行设计,但是有一种方法可以确定MyControl本身是否在设计中,而不是在设计时在from上进行操作。 ?



为了进一步说明,在MyControl类中,我试图在设计组件本身时区分设计时:

c# - 确定自定义Winforms控件的设计时上下文-LMLPHP

在设计时将组件从工具箱添加到表单中时:

c# - 确定自定义Winforms控件的设计时上下文-LMLPHP

最佳答案

您可以检查控件是否位于设计器的根目录中。
您可以获取IDesignerHost服务,然后检查RootComponent属性以查看您的控件是否是当前设计器的根组件。

using System.Windows.Forms;
using System.ComponentModel.Design;
public partial class MyBaseControl : UserControl
{
    public MyBaseControl()
    {
        InitializeComponent();
    }

    public bool IsRootDesigner
    {
        get
        {
            var host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
            if (host != null)
                return host.RootComponent == this;

            return false;
        }
    }
}

10-06 05:23
查看更多