Winforms Form Constructor vs Load event

2019-01-15 18:55发布

问题:

When a form loads, the code needs to do things like setup datagrids, comboboxes, set the title, etc. I've tended to always use the load event rather than the new (constructor). Are there any guidelines for which one is best for which activities?

回答1:

A call to InitializeComponent is automatically inserted in the constructor of your form/page. InitializeComponent is the auto-generated method that

  • creates the various UI elements on your winform / XAML page
  • initializes their properties with the values stored in the resource file

So anything related to UI arrangement/modifications should go after this call. When you do this in an override of Form.OnLoad , you're assured that the UI is ready to go (InitializeComponent has been called)... so I'd vote for sticking to OnLoad for UI.
Creating non-UI members, constructor would be the place I'd first look at.



回答2:

Bear in mind that anything in the constructor of a form will be created/executed at that forms creation. i.e. at:

Form frm = new Form();

Whereas anything in the Load event will occur only when the form is shown i.e. frm.Show();



回答3:

Basically you want your constructor to be as light-weight as possible. I try to put most things in the Load event handler as the UI elements have been created and are usable at this time. However, I usually instantiate class objects etc. in the constructor as it is actually part of constructing the object. Sometimes you can't put things in one place or the other but for the times when you can, you should just put them where it seems most appropriate.