确定自定义winforms控件的设计时上下文

时间:2016-03-04 05:31:05

标签: c# .net winforms user-controls windows-forms-designer

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

public class MyBaseControl : Control
{
     ...
}

扩展如下:

public class MyControl : MyBaseControl
{
     ...
}

通过检查this.DesignMode属性标志确定控件是否在视觉上设计是相当简单的,但是否有办法确定MyControl本身是否正在设计,而不是在设计时被操纵?

为了提供额外的说明,在MyControl类中,我试图区分设计组件本身的设计时间:

"Control" designer

当组件在设计时从工具箱添加到表单时

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以检查控件是否为设计器中的root用户 您可以获取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;
        }
    }
}