问题描述
我是新来的Web表单用户控件,我需要一个事件添加到控件,以便使用控制开发人员可以添加事件处理此事件。什么是去这样做的最佳方式?
I am new to user controls in webforms and I need to add an event to the control so that developers using the control can add event handlers to this event. What is the best way to go about doing this?
这是控制一个自定义上传控制。控制文件上传到Web服务异步,并存储在一个隐藏字段成功上传的文件列表。在接下来的文章后面,我想从申请表收集在这个隐藏字段阅读,如果它不为null,则我想解雇上传成功的事件。
This control is a custom uploader control. The control uploads files to a web service asynchronously and stores a list of files that uploaded successfully in a hidden field. On the next post back I would like to read from this hidden field in the request form collection, and if it's not null then I'd like to fire a successful upload event.
任何帮助很多AP preciated。谢谢!
Any help is much appreciated. Thank you!
很抱歉,如果我是一个有点模糊。我要寻找一个服务器端的事件,我可以开火。我只是不熟悉创建它们。
Sorry if I was a bit vague. I am looking for a server-side event that I can fire. I am just not familiar with creating them.
推荐答案
首先通过为事件参数创建类开始。
First start off by creating a class for your event arguments.
// this can house any kind of information you want to send back with the trigger
public class MyNewEventArgs : EventArgs { ... }
接下来,创建该控件的类的事件。这是在使用委托做的,而事件本身。
Next, create the event on the control's class. this is done using a delegate, and the event itself.
// event delegate handler
public delegate void MyNewEventHandler(object s, MyNewEventArgs e);
// your control class
public class MyControl : Control
{
// expose an event to attach to.
public event MyNewEventHandler MyNewEvent;
接下来,你需要从你的code触发事件。我们通过抓住事件,检查用户,然后触发做到这一点。
Next you need to fire the event from your code. We do this by grabbing the event, checking for subscribers, then triggering.
// grab a copy of the subscriber list (to keep it thread safe)
var myEvent = this.MyNewEvent;
// check there are subscribers, and trigger if necessary
if (myEvent != null)
myEvent(this, new MyNewEventArgs());
更多信息可以在MSDN上找到在的。
这篇关于如何创建在web表单用户控件自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!