简体   繁体   English

.NET C#-用于事件接线的表单代码与设计器代码文件

[英].NET C# - Form versus Designer code files for Event Wiring

I was just curious how others work with this kind of WinForm code in C#. 我只是很好奇其他人如何在C#中使用这种WinForm代码。 Lets say I have a Form lets call it Form1. 可以说我有一个Form,可以称之为Form1。 And I have a DataGridView called dgvMain. 我有一个名为dgvMain的DataGridView。

Where do you put the code: 您将代码放在哪里:

this.dgvMain.CellEndEdit += new DataGridViewCellEventHandler(dgvMain_CellEndEdit);

Do you put it in the Form1 code or the Form1 designer code? 您将其放在Form1代码还是Form1设计器代码中? Should this "event wiring" code go in the Form1_Load method? 此“事件关联”代码是否应放入Form1_Load方法中?

The reason I am ask is... if you double click the DataGridView the IDE inserts the code: 我问的原因是...如果您双击DataGridView,IDE将插入代码:

 this.dgvMain.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMain_CellContentClick);

into the designer code. 进入设计器代码。 Should your "event wiring" code be in two places? 您的“事件接线”代码应该放在两个地方吗?

Short answer is yes. 简短的回答是。

Longer answer is that .designer.cs is there for code generated by the designer. 更长的答案是.designer.cs存在于设计器生成的代码中。 if you put your own code in there, it has a chance of getting overwritten, screwing up the design time stuff in visual studio, and lowers maintainability because nobody expects custom code to be in there. 如果您在其中放置自己的代码,则可能会被覆盖,从而使Visual Studio中的设计时间变得混乱,并降低了可维护性,因为没有人期望自定义代码会出现在其中。

This is a touchy subject. 这是一个敏感的话题。 In 1.1, there where regions for this in your forms file, but a lot of the time, the code would be over written by the designer. 在1.1中,表单文件中的哪些区域存在,但是很多时候,设计人员会覆盖代码。 I'm speaking from webforms experiance, but I would only gather that it would be the same elsewhere. 我是从webforms经验上讲的,但我只能认为在其他地方也是如此。

Now, you actually put the eventname in the form itself (it's one of the properties on the forms designer), and the code generator will push out the += event handler thingies in the partial class. 现在,您实际上将事件名称放入了表单本身(它是表单设计器上的属性之一),并且代码生成器将在局部类中推出+ =事件处理函数。 I hate it this way, but it is what it is. 我讨厌这种方式,但事实就是如此。

I use the Designer for all event related to Component. 我将Designer用于与Component相关的所有事件。

I use the code for all object event. 我将代码用于所有对象事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM