假设我有一个自定义WinForms控件:
public class MyBaseControl : Control
{
...
}
扩展如下:
public class MyControl : MyBaseControl
{
...
}
通过检查
this.DesignMode
属性标志,很容易确定控件是否在视觉上进行设计,但是有一种方法可以确定MyControl
本身是否在设计中,而不是在设计时在from上进行操作。 ?为了进一步说明,在
MyControl
类中,我试图在设计组件本身时区分设计时:在设计时将组件从工具箱添加到表单中时:
最佳答案
您可以检查控件是否位于设计器的根目录中。
您可以获取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;
}
}
}