[英]Why is New() firing twice on my inherited controls? (winforms)
Step 1 : Create inhered control class 第1步 :创建内联控件类
Public Class Test_Control
Inherits ListBox
Public Sub New()
Items.Add("test")
End Sub
End Class
Step 2 : Drag class to form in the designer 第2步 :在设计器中将类拖到窗体中
Step 3 : Run the project 第3步 :运行项目
Result : 结果 :
Why is this happening?! 为什么会这样?! I am completely stumped here.. I have googled and googled and I cannot find any solution or answer to this. 我完全被困在这里..我用谷歌搜索和谷歌搜索,我找不到任何解决方案或答案。
This is causing some major issues for me. 这给我带来了一些重大问题。 I am simply trying to add an initial "Select one..." option to every newly created Combobox. 我只是想为每个新创建的Combobox添加一个初始的“Select one ...”选项。 Same thing happens with every inherited control class, regardless of control type (textbox/combobox/listbox/etc). 每个继承的控件类都会发生同样的事情,无论控件类型如何(textbox / combobox / listbox / etc)。
Same thing happens if I use a message box within New(). 如果我在New()中使用消息框,也会发生同样的事情。 Two message boxes appear as soon as I run my application. 运行应用程序后会立即显示两个消息框。
You need to tell the designer to not serialize the items collection: 您需要告诉设计者不要序列化项目集合:
Public Class Test_Control
Inherits ListBox
Public Sub New()
Items.Add("test")
End Sub
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Items As ListBox.ObjectCollection
Get
Return MyBase.Items
End Get
End Property
End Class
As far as the two message boxes go, MessageBoxes are just not a good debugging tool. 就两个消息框而言,MessageBoxes不是一个好的调试工具。 You are probably getting the WinForms designer calling new while the runtime calling new, too (or something like that). 您可能正在让WinForms设计器调用new,而运行时调用new(或类似的东西)。
The first test
is from the designer and you are adding a second one in the constructor. 第一个test
来自设计器,您在构造函数中添加第二个test
。
Either remove the test
from the designer or clear the items in the constructor before adding, like this: 在添加之前从设计器中删除test
或清除构造函数中的项目,如下所示:
Items.Clear()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.