Winforms Form Constructor vs Load event

冷暖自知 提交于 2019-11-26 22:01:50

问题


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.



来源:https://stackoverflow.com/questions/264396/winforms-form-constructor-vs-load-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!