在使用.net Winform Designer时,如何处理UserControls构造函数中的异常?

时间:2021-03-08 15:52:51

When you load an UserControl in the WinForm designer, VisualStudio executes the InitializeComponent() method of the control, but not its constructor. This really makes a difference because it's quite common to have some code in the constructor which cannot run at design time.

在WinForm设计器中加载UserControl时,VisualStudio将执行控件的InitializeComponent()方法,但不执行其构造函数。这确实有所不同,因为在构造函数中有一些代码在设计时无法运行是很常见的。

Unfortunately, when you add an UserControl to another control, VisualStudio runs the InitializeComponent() method of the parent control, which calls the constructors of the child controls, and if you've got an exception in those constructors, you're stucked.

不幸的是,当您将UserControl添加到另一个控件时,VisualStudio运行父控件的InitializeComponent()方法,该方法调用子控件的构造函数,如果您在这些构造函数中有异常,则会被卡住。

How do you deal with this problem?

你是如何处理这个问题的?

4 个解决方案

#1


wrap the runtime only parts with:

仅包含运行时的部分:

If Not me.DesignMode Then
  'Runtime only here
End If

#2


I found a solution in CodeProject that works for me:

我在CodeProject中找到了一个适合我的解决方案:

if (System.ComponentModel.LicenseManager.UsageMode != 
    System.ComponentModel.LicenseUsageMode.Designtime)
{
    // Runtime only here
}

#3


Why not use the OnLoadEvent in this scenario?

为什么不在这种情况下使用OnLoadEvent?

#4


The workaround I'm using is to put my runtime initialization code in an InitializeRuntime() method, which I recursively call from the toplevel constructor. This solves the problem, but I always have to remember to add the call to InitializeRuntime() for every single UserControl I add instead of just drag'n'dropping the component using the designer.

我正在使用的解决方法是将我的运行时初始化代码放在InitializeRuntime()方法中,我从顶层构造函数中递归调用。这解决了这个问题,但我总是要记住为我添加的每个UserControl添加对InitializeRuntime()的调用,而不是仅仅使用设计器拖放组件。

#1


wrap the runtime only parts with:

仅包含运行时的部分:

If Not me.DesignMode Then
  'Runtime only here
End If

#2


I found a solution in CodeProject that works for me:

我在CodeProject中找到了一个适合我的解决方案:

if (System.ComponentModel.LicenseManager.UsageMode != 
    System.ComponentModel.LicenseUsageMode.Designtime)
{
    // Runtime only here
}

#3


Why not use the OnLoadEvent in this scenario?

为什么不在这种情况下使用OnLoadEvent?

#4


The workaround I'm using is to put my runtime initialization code in an InitializeRuntime() method, which I recursively call from the toplevel constructor. This solves the problem, but I always have to remember to add the call to InitializeRuntime() for every single UserControl I add instead of just drag'n'dropping the component using the designer.

我正在使用的解决方法是将我的运行时初始化代码放在InitializeRuntime()方法中,我从顶层构造函数中递归调用。这解决了这个问题,但我总是要记住为我添加的每个UserControl添加对InitializeRuntime()的调用,而不是仅仅使用设计器拖放组件。