在 VB.NET 的 Windows 窗体控件中,InitializeComponent 何时何地被调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1042706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where and when is InitializeComponent called in Windows Forms control in VB.NET?
提问by Konstantinos
I'm doing a Windows Forms project in VB.NET, but VB.NET is completely new to me, I'm primarily a C# developer.
我正在 VB.NET 中做一个 Windows 窗体项目,但 VB.NET 对我来说是全新的,我主要是 C# 开发人员。
In C# Windows Forms, a user control's InitializeComponent is called from the form's/control's constructor. When I create same scenario in VB.NET I don't get a constructor, and I can't locate a place where InitializeComponent is called.
在 C# Windows 窗体中,用户控件的 InitializeComponent 是从窗体/控件的构造函数中调用的。当我在 VB.NET 中创建相同的场景时,我没有得到构造函数,也找不到调用 InitializeComponent 的地方。
I need to call my code between InitializeComponent and when the control's Load
event is raised, preferably still in the control's constructor. How do I do this in VB.NET?
我需要在 InitializeComponent 和Load
引发控件事件之间调用我的代码,最好仍然在控件的构造函数中。我如何在 VB.NET 中做到这一点?
回答by Konstantinos
Go to View Code in your form, and from the right drop down and select "New Method".
转到表单中的查看代码,然后从右侧下拉菜单中选择“新方法”。
There you can see where InitializeComponent is called and insert your logic.
在那里您可以看到调用 InitializeComponent 的位置并插入您的逻辑。
Your code, if your form is empty, should look like this:
如果您的表单为空,您的代码应如下所示:
Public Class Form1
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
End Class
回答by Rad
In VB.NET the constructor is called New
and has the following basic signature.
在 VB.NET 中,构造函数被调用New
并具有以下基本签名。
Public Sub New()
End Sub
You can of course override it and add custom parameters.
您当然可以覆盖它并添加自定义参数。
Visual Studio 2008, BTW, will remind you to put the InitializeComponent()
method in the constructor in case you forget, as omitting that will lead to strange behaviors of your controls.
顺便说一句,Visual Studio 2008 会提醒您将该InitializeComponent()
方法放在构造函数中以防您忘记,因为省略会导致您的控件出现奇怪的行为。