Winforms 表单构造函数 vs 加载事件 [英] Winforms Form Constructor vs Load event

查看:31
本文介绍了Winforms 表单构造函数 vs 加载事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个表单加载时,代码需要做一些事情,比如设置数据网格、组合框、设置标题等.我倾向于总是使用加载事件而不是新的(构造函数).对于哪种活动最适合哪种活动,是否有任何指导方针?

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?

推荐答案

对 InitializeComponent 的调用会自动插入到表单/页面的构造函数中.InitializeComponent 是自动生成的方法,

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

  • 在您的 winform/XAML 页面上创建各种 UI 元素
  • 使用资源文件中存储的值初始化它们的属性

因此,任何与 UI 安排/修改相关的事情都应该在此调用之后.当您在 Form.OnLoad 的覆盖中执行此操作时,您可以确信 UI 已准备就绪(已调用 InitializeComponent)...所以我会投票支持在 UI 上坚持 OnLoad.
创建非 UI 成员,构造函数将是我首先考虑的地方.

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.

这篇关于Winforms 表单构造函数 vs 加载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆