Microsoft Visual Studio 和 C#:如何以可视方式向控件添加事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1135299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Microsoft Visual Studio and C#: How to Visually Add Events to Controls?
提问by morrog
Perhaps this is a stupid question, but for the life of me I cannot find a way to do this.
也许这是一个愚蠢的问题,但对于我的生活,我找不到办法做到这一点。
How would one go about adding an event handler to a control in a form in Microsoft Visual Studio (2008) with C#?
如何使用 C# 在 Microsoft Visual Studio (2008) 中的表单中向控件添加事件处理程序?
I can do it manually, but opening the Designer.cs file for the Form, but I cannot find a way to do it through the interface. In MSVC 6, with C++ and MFC, you could right click or some other action, and find a list of all the possible events for that control. Then you select it and it would bring up window letting you create a method to associate with that event. In VB it was even easier, you could do it in the code and it listed all the events in the method drop downs.
我可以手动完成,但打开表单的 Designer.cs 文件,但我找不到通过界面执行此操作的方法。在 MSVC 6 中,使用 C++ 和 MFC,您可以右键单击或执行其他操作,然后找到该控件的所有可能事件的列表。然后你选择它,它会弹出一个窗口,让你创建一个与该事件关联的方法。在 VB 中它更容易,你可以在代码中完成,它在方法下拉列表中列出了所有事件。
However, I cannot find anything of the sort in 2008 with C#. Intellisense helps fill in the correct method information. However, it always creates the method in the Designer.cs file, not the other half of the partial class where it should be.
但是,我在 2008 年用 C# 找不到任何类似的东西。Intellisense 有助于填写正确的方法信息。但是,它始终在 Designer.cs 文件中创建方法,而不是在应位于的部分类的另一半中。
Thank you.
谢谢你。
采纳答案by womp
In the designer, click the control of interest.
在设计器中,单击感兴趣的控件。
In the properties window (hit F4 to bring it up), there should be a little lightning bolt icon. Clicking the icon takes you to the list of available events for that control. Double-clicking the event name will wire up a stub handler and take you to the code-behind for it.
在属性窗口中(按 F4 调出),应该有一个小闪电图标。单击该图标可转到该控件的可用事件列表。双击事件名称将连接一个存根处理程序并将您带到它的代码隐藏处。
Edit: the astute reader will see that the posted screenshot is for a web app (whups), but it's the exact same thing for a winforms app.
编辑:精明的读者会看到发布的屏幕截图是针对网络应用程序(whups)的,但对于 winforms 应用程序来说,这完全相同。
回答by jpoh
All you have to do is to have the form/control open in designer view, have the control in question in focus/selected, open up the properties view and flick over to the events tab. Double click on the event that you're interested in handling.
您所要做的就是在设计器视图中打开表单/控件,让有问题的控件处于焦点/选中状态,打开属性视图并轻弹到事件选项卡。双击您有兴趣处理的事件。