系统定义了一个基类控件BaseControl,该类实现控件的通用方法以及进行依赖注入
public partial class BaseControl : UserControl
{
//依赖注入的实体类
public TestClass testClass{ get; set; }
//依赖注入的方法
public void InitInjection()
{
//to do init injection
}
}
子类控件TestControl继承基类控件BaseControl
public class TestControl : BaseControl
{
//to do ...
}
当界面拖拽TestControl到界面或者打开设计视图时,会在界面的designer.cs文件中生成依赖注入的实体类的实例化方法
//TestForm.Designer.cs文件
public class TestForm
{
...
private void InitializeComponent()
{
TestClass testClass = new TestClass();
...
}
}
解决方案:
通过系统System.ComponentModel.Component下的DesignMode来控制打开设计视图或者拖拽控件时,不进行依赖注入
public partial class BaseControl : UserControl
{
public void InitInjection()
{
if(!DesignMode)
{
//to do init injection
}
}
}
调试时发现,BaseControl中的DesignMode仍为False,这里引用一位哥们的总结:“也就是说一个控件只有在它自己被拖拽到设计器的时候,其 DesignMode 才是真,如果它被包含在其他控件中被加入到设计器,那么那个控件才是在设计模式,而它不是!换句话说,DesignMode 并不能反映当前环境是否是运行时,它只能告诉你,这个控件当前是不是直接被设计器操作(嵌套的已经不算了) 。”
因而需要对DesignMode进行重写,使之符合我们的期望值
protected new bool DesignMode
{
get
{
bool returnFlag = false;
#if DEBUG
if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
returnFlag = true;
else if (System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToUpper().Equals("DEVENV"))
returnFlag = true;
#endif
return returnFlag;
}
}