界面和转换,表单和面板 [英] Interfaces and Casting, Forms and Panels
问题描述
我有一个只能在特定情况下实现的控件(例如:只能添加到特定面板或窗体的ControlCollection中).为此,我重写了控件的OnParentChanged方法,以查看父级是否已实现给定的接口:
I have a control that can only be implemented in specific situations (eg: it can only be added to the ControlCollection of a specific panel or form). To achieve this, I have overridden the OnParentChanged method of the control to see if the parent has implemented a given interface:
Public Class MyControl
Private MyParentControl As IMyControlInterface
Protected Overrides Sub OnParentChanged(ByVal e As System.EventArgs)
If MyBase.Parent IsNot Nothing Then
Me.MyParentControl = TryCast(MyBase.Parent, IMyControlInterface)
If Me.MyParentControl Is Nothing Then
Throw New Exception("Control can only be added to an object that implements IMyControlInterface.")
End If
End If
MyBase.OnParentChanged(e)
End Sub
End Class
我试图启用此代码,以便可以将控件从Visual Basic设计器的控件面板拖动到设计图面上.我将面板定义为:
I am trying to enable this code so that the control can be dragged from the controls panel of the Visual Basic designer to the design surface. I have defined the panel as:
Public Class MyControlPanel
Inherits Panel
Implements IMyControlInterface
...
End Class
表单是由设计人员生成的(即:表单的PartialClass扩展名),即:
and the form is designer-generated (ie: a PartialClass extension of the form), to wit:
Public Class Form1
Implements IMyControlInterface
...
End Class
由于某些原因,当我将MyControl从控件面板拖到窗体时,它会调用该异常.但是,当我将MyControlPanel拖到窗体上,然后将MyControl拖到MyControlPanel1(设计者给定的名称)上时,它将接受被拖动的控件.
我不明白为什么一个调用接受添加,而另一个则不接受.有谁对此有任何想法吗?
在此先感谢您的帮助...
For some reason, when I drag MyControl to the form from the controls panel, it invokes the exception. However, when I drag MyControlPanel to the form, and then drag MyControl onto MyControlPanel1 (the name given by the designer), it accepts the dragged control.
I do not understand why one invocation accepts the add, while the other does not. Does anyone have any idea about this?
I thank you in advance for your help...
推荐答案
请参阅本页上的答案1",因为它仅说明了您的痛苦:http://stackoverflow.com/questions/4546311/c-windows-forms-design -time-form-constructor-not-调用 [ ^ ]
Please see "Answer 1" on this page as it just about explains your pains: http://stackoverflow.com/questions/4546311/c-windows-forms-design-time-form-constructor-not-called[^]
这种行为是设计使然.VisualStudio中的表单设计器无法实例化所设计的类,而是将其直接父级实例化.无法更改此行为.如果需要在设计期间执行某些逻辑,则可以必须创建一个单独的祖先,封装该逻辑并从中继承."
Ondrej Tucny 在stackoverflow上
"This behavior is by design. The form designer in Visual Studio cannot instantiate the class being designed — instead, it instatiates its immediate parent. There is no way to change this behavior. If you need some logic to be executed during design time, you have to create a separate ancestor encapsulating that logic and inherit from it."
Ondrej Tucny on stackoverflow
这篇关于界面和转换,表单和面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!