Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c# - How should the Form.Load event be used compared to its constructor method?

When initializing properties of controls or other values related to a Form I have a tendency to switch back and forth between initializing the values in the Form's constructor and then later when the Form.Load event is evoked.

What is the generally accepted usage of a Forms constructor vs it's Form.Load event? With other classes I would do all initialization in the constructor. Yet in in VS when you double click on a Form it jumps you to an event handler for the Form.Load event not the constructor. This leads me to believe that it's preferable to do all the initialization after the Load event instead of the constructor.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it is a wee bit sad that it works that way. It made a lot of sense at the time, now 10 years ago already. Windows Forms was targeted to be a replacement for VB6, the dominant point-and-click UI designer at the time. And Form_Load was important in VB6, that's where you customized the form view.

That wasn't really appropriate from the get-go, the Form class has a true-blooded constructor. And you can set control properties in the constructor before the actual native Window control gets created. There's a ton of code in WF to make that work. Code that the designer relies on, it sets these properties before the Load event fires. It is very efficient to do so, many controls get a lot slower when they need to be updated after their window is created. Like ListView and TreeView.

There are few reasons to not use the constructor yourself, like the designer does, especially since the C# IDE doesn't try to hide the constructor. Except one: you need the Load event when you write the kind of code that requires knowing the actual form size. That size isn't known until the window actually gets created, the Load event is the earliest after that. That ought to be rare.

And of course, if you do want to use Load then you override OnLoad instead of using the Load event. That would be another one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...