将Winforms控件添加到表单时是否会引发事件

Dan*_*ely 8 c# events custom-controls winforms

我正在研究一些自定义Control类,需要对它们进行一些初始化,这取决于它们是否被添加到表单中.发生这种情况时是否会发生事件?

我认为这个样本应该足以显示我正在尝试做的事情:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

事实证明这比我最初意识到的要困难得多,我想我将不得不结合Bolu和Mike Dour的建议.问题在于,虽然有些MyControls直接添加到表单中,但是Bolu的解决方案可以完美地运行.其他人被添加到面板而不是直接添加到表单.我想我已经拼凑了一个解决方案,涉及Bolu的前一种情况的解决方案,并进行了一些修改,以处理事件是由被添加的面板而不是其MyControl内部引发的情况,以及Mikes来处理MyControls的情况构造函数运行完毕后添加到面板中.在我确信它有效之前,我必须在明天早上再测试一下.

当我尝试在设计器中使用他的建议时,Bolu请求的错误消息:

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)
...'
Run Code Online (Sandbox Code Playgroud)

当我收到错误时,构造函数到位.

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
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 10

试试这个ParentChanged活动.