【发布时间】:2009-12-15 11:06:21
【问题描述】:
我的表单中有一个特殊标签,它应该在工具提示中显示一些文本。 标签在表单中被声明为私有类(嵌套控件),并且应该“看到”父表单的 ToolTip 控件。
这里是代码。当然,我在这里得到错误,因为构造函数是在所有者表单控件集合中添加私有控件之前调用的......
编辑: 有没有可能在构造函数中不传递form1或toolTip控件?
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
FormLabel myFormLabel = new FormLabel("uraaaaa!");
this.Controls.Add(myFormLabel);
myFormLabel.Location = new Point(20, 20);
}
private class FormLabel : Label
{
public FormLabel(string toolTip) : base()
{
this.Text = toolTip.ToUpperInvariant();
(this.FindForm() as Form1).toolTip1.SetToolTip(this, toolTip);
}
}
}
}
【问题讨论】:
-
您为什么不想要将正确的表单传递给构造函数?这是实现您想要的最简单的方法,并且不需要 FindForm/ParentForm “准备好”。
-
是的,但这不是一个公共类,在你的情况下,我可以将参数传递给 Form1 的另一个实例......最后,我不能否认你的建议有效,但是恕我直言,这不是优雅的解决方案。
-
@serhio:哪方面不优雅?它为类提供了它需要的所有信息,而不是依赖于初始化的确切时间等。因此它不那么脆弱,更简单......有什么不喜欢的?
标签: .net winforms .net-2.0 nested accessor