简体   繁体   English

控件的等效形式“ On_Load”是什么?

[英]What is the Form “On_Load” equivalent for Controls?

I have a listBox that I would like to carry out a method when its loaded up, although I can't use the Form "On_Load" trigger, since the ListBox is within a TabControl. 我有一个listBox,我想在加载时执行一个方法,尽管我不能使用Form“ On_Load”触发器,因为ListBox在TabControl内。

Is there a way of getting a method to execute when the object initializes? 有没有一种方法可以让对象初始化时执行?

The closest analog for controls is the HandleCreated event. 与控件最接近的模拟是HandleCreated事件。 This will fire when the underlying control handle is created, which is slightly before the Loaded event of the parent window would fire. 这将在创建基础控件句柄时触发,即稍早于父窗口的Loaded事件触发之前。

As @SLaks stated, you could put in your class's constructor. 如@SLaks所述,您可以放入类的构造函数。 However, if what you want to prepare relies on other elements in the form, you can add to the event handler queue at the end of a form loading, but before its actually presented to the user. 但是,如果要准备的内容依赖于表单中的其他元素,则可以在表单加载结束时将其添加到事件处理程序队列中,但要在它实际呈现给用户之前添加。

In the constructor code of your form (not the designer code), add to the load event, then add your own custom function 在表单的构造函数代码(而不是设计器代码)中,添加到load事件,然后添加自己的自定义函数

public partial class frmYourForm : Form
{
    public frmYourForm()
    {
       Load += YourPreparationHandler;
    }

    private void YourPreparationHandler(object sender, EventArgs e)
    {
        // Do you code to prepare list, combos, query, bind, whatever
    }
}

您可以使用HandleCreated事件吗?

Have the same problem, the previous answers apply well, for a single case. 有相同的问题,对于单个情况,前面的答案很适用。

But, I require to do something in most controls, in several forms, in an app. 但是,我需要在大多数控件中以某种形式在应用程序中执行某些操作。 Solved by using an interface: 通过使用接口解决:

interface IOnLoad
{
  void OnLoad();
}

And added to descendant control: 并添加到后代控件中:

public partial class MyButton : Button, IOnLoad
{
  void OnLoad() { // call "OnLoadDelegate" }
}

public partial class MyForm : Form
{

  public void MyForm_Load(...) {
    foreach(Control eachControl in Controls) {
      if (eachControl is IOnLoad) {
        IOnLoad eachOnLoadControl = (IOnLoad)eachControl;
        eachOnLoadControl.OnLoad();
      }
    } // foreach
  }
} // class

Its more complex, but it suit my requirements. 它比较复杂,但是符合我的要求。

You can just put your code in the constructor. 您可以将代码放入构造函数中。

You usually don't need to wait for any initialization. 通常,您不需要等待任何初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM