在哪种情况下,当最初加载WinForms自定义控件(从TextBox继承)时,可靠地引用父窗体是否可行和合适?
在搜索了一下之后,我发现关于这个领域的一个讨论是.NET WinForms Custom Control: how to get a reference to the containing form。具体来说,adrift发布的内容涉及到一个问题,即在将自定义控件添加到父窗体(以及OnParentChanged事件触发)之前,FindForm将返回空。
基于此,建议使用OnParentChanged事件。不幸的是,我发现如果自定义控件包含在另一个控件(例如Panel)中,那么这个容器不一定会添加到表单的控件集合中,而且即使在自定义控件的FindForm事件中,这个容器也会返回null。
因此,我想知道是否有更好的事件可供使用,从而可靠地允许使用FindForm返回自定义控件的父窗体(即使它位于另一个容器控件中)。
发布于 2014-02-07 19:05:18
根据我对问题的理解,您可能可以在自定义控件上实现ISupportInitialize接口。
这将允许窗体的InitializeComponent()方法调用控制代码。
例如,从Button派生的这个简单的用户控件:
class MyButton : Button, ISupportInitialize
{
public void BeginInit()
{
var parent = this.TopLevelControl;
}
public void EndInit()
{
var parent = this.TopLevelControl;
}
}
在窗体上放置时,设计器代码将如下所示:
private void InitializeComponent()
{
this.myButton1 = new Quartz1.MyButton();
((System.ComponentModel.ISupportInitialize)(this.myButton1)).BeginInit();
this.SuspendLayout();
//
// myButton1
//
this.myButton1.Location = new System.Drawing.Point(371, 338);
this.myButton1.Name = "myButton1";
this.myButton1.Size = new System.Drawing.Size(75, 23);
this.myButton1.TabIndex = 4;
this.myButton1.Text = "myButton1";
this.myButton1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1012, 440);
this.Controls.Add(this.myButton1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.myButton1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
如您所见,表单初始化完成后,将在控件上调用EndInit()。此时,this.TopLevelControl
将不是空的。
我不确定这是否是你想要的,如果不是,请毫不犹豫地在你的问题中添加更多的上下文。
干杯
https://stackoverflow.com/questions/21640416
复制相似问题