Winform 自定义控件设计模式下使用DesignMode不进行依赖注入

本文介绍了在Winform自定义控件中如何利用DesignMode属性防止在设计视图中进行不必要的依赖注入。系统基类控件BaseControl包含通用方法和依赖注入,子类TestControl继承自BaseControl。当TestControl被拖拽到界面或在设计视图中打开时,会导致设计时生成依赖注入的实例。通过检查System.ComponentModel.Component.DesignMode属性并重写其行为,可以确保在设计模式下不执行依赖注入,从而解决这个问题。
摘要由CSDN通过智能技术生成

系统定义了一个基类控件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
{
    pu
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值