我正在处理一些自定义的Control
类,并且需要对它们进行初始化,而这些初始化依赖于它们被添加到表单中。发生这种情况时会发生事件吗?当Winforms控件被添加到表单时,Winforms控件是否引发事件
我觉得这个样本就足够了,以显示我想要做的事:
public interface IMyForm
{
ISomeObject SomeObject {get; set; }
}
class MyForm : IMyForm
{
//eg InitializeComponent() as well as several others called at later points
private MethodThatAddsAControl()
{
MyControl newControl = new MyControl();
//other initialization as needed
//does this raise an event in MyControl I can use to call
//InitializationAfterBeingAddedToForm()?
this.Controls.Add(newControl);
}
}
class MyControl : Control
{
InitializationAfterBeingAddedToForm()
{
//can't be done in the constructor because at that point FindForm() will return null
(FindForm() as IMyForm).SomeObject.AnEvent += new EventHandler(SomeObject_AnEvent);
}
}
这是谈到了更加困难比我初步实现了,我想我将不得不结合博卢和麦克杜尔的建议。问题是,虽然有些MyControl
被直接添加到表单,在这种情况下Bolu的解决方案完美地工作。其他人被添加到面板,而不是直接添加到表单。我想我已经拼凑了一个包含Bolu解决方案的前一种解决方案,并对其进行了一些修改,以处理事件由正在添加的面板而不是其中的MyControl
引发的情况,而Mikes则负责处理MyControl
s在构造函数完成运行后被添加到面板中。我必须在明天早上进行更多测试,然后才能确信它已经奏效。通过波鲁请求时,我尝试用他的建议在设计
错误消息:
Failed to create component 'MyControl'. The error message follows:
'System.MissingMethodException: Constructor on type 'MyNamespace.MyControl' not found.
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.ComponentModel.Design.DesignSurface.CreateInstance(Type type)
at Microsoft.VisualStudio.Design.VSDesignSurface.CreateInstance(Type type)
at System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.CreateComponent(Type componentType, String name)
at System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.CreateComponent(Type componentType)
at System.Drawing.Design.ToolboxItem.CreateComponentsCore(IDesignerHost host)
at System.Drawing.Design.ToolboxItem.CreateComponentsCore(IDesignerHost host, IDictionary defaultValues)
...'
和到位的构造函数时,我得到了错误。
public MyControl(Form parent)
{
_parent = parent as IMyForm;
parent.ControlAdded += new ControlEventHandler(parent_ControlAdded);
Initialize(); //does rest of initialization
}
public TimelineControl(Form parent, Panel container)
{
_parent = parent as IMyForm;
container.ControlAdded += new ControlEventHandler(parent_ControlAdded);
Initialize(); //does rest of initialization
}
编辑我的回答 – Bolu 2010-11-24 09:54:10