Editing the InitializeComponent() method C#

北战南征 提交于 2020-01-17 04:46:06

问题


I've gone through multiple resources on trying to find the use cases of when to manually add code to InitializeComponent, but haven't found anything concrete. This suggests we shouldn't do it - The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified

In the past, I had always used the form designer and never needed to manually make changes to InitializeComponent(). However at my new firm, the tech lead has completely ignored the form designer and manually added most UI elements within InitializeComponent (i.e. it has either been heavily edited, or completely re-written to the extent that the Designer can't recreate the GUI in VS, but the GUI is visible and fully functional at when the code is executed)

What is the advantage of not using the form designer? Is it just a matter of preference? Is manually editing/rewriting InitializeComponent for simple UI elements a good practice?

Thanks!


回答1:


There are only a few reasons why one might need to edit InitializeComponent, such as:

  1. To correct bugs introduced by a bad toolbox item designer.
  2. To remove all traces of a control that cannot be deleted from the VS designer. (This has to be done carefully.)
  3. To make quick "designer friendly" tweaks: changing a property value, adding a property setting, or removing a property setting. When adding a setting, I make sure it looks just like the designer-generated code.

After editing InitializeComponent, I always save & switch back to Designer mode to make sure I didn't break anything.

Any manual initialization code should be added outside InitializeComponent, e.g. OnLoaded() in a WinForms form or user control. As for fixing existing forms, it may be simple or nearly impossible depending on how complicated the form is, especially if controls have been added manually and required initialization methods (such as SuspendLayout, BeginInit) aren't being called.



来源:https://stackoverflow.com/questions/33348930/editing-the-initializecomponent-method-c-sharp

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