[英]Exposing Events from asp.net usercontrols to container web forms page
How does one actually expose a abstracted event from asp.net usercontrol[ascx file] to the container webforms page. 如何实际将抽象事件从asp.net usercontrol [ascx文件]公开到容器Webforms页面。 This is my scenario, 这是我的情况
I created a webforms usercontrol a ascx file and put a databound checkboxlist with a validator to validate it(I know this could be done webforms itself why a usercontrol u ask, but it's a scenario) 我创建了一个webforms用户控件一个ascx文件,并在数据绑定的复选框列表中添加了一个验证器以对其进行验证(我知道这可以由webforms本身完成,为什么您要问一个用户控件,但这是一种情况)
Now i wanted to expose a event to the container page called OnValidating
which would produce the result of validation 现在我想向容器页面公开一个名为OnValidating
的事件,该事件将产生验证结果
signature of the event is below: 该事件的签名如下:
public delegate void Validating(object source,EventArgs e);
public event Validating OnValidating;
public void InvokeOnValidating(EventArgs e)
{
Validating handler = OnValidating;
if (handler != null) handler(this, e);
}
As per the msdn documentation, the page framework handles the event subscribing and unsubscribing. 根据msdn文档,页面框架处理事件的订阅和取消订阅。 So all i need to do was invoke the event when validation fails. 所以我要做的就是在验证失败时调用事件。 Great i was happy but, 太好了,我很高兴,但是
I couldn't show up the event in the properties window when all other public propertes did 当其他所有公共属性都出现时,我无法在属性窗口中显示该事件
Why the hell is my event invoker[InvokeOnValidating]
, event delegate[Validating]
shown in intellisense list when i type usercontrolid.
为什么当我键入usercontrolid.
时,智能提示列表中会显示我的event invoker[InvokeOnValidating]
和event delegate[Validating]
usercontrolid.
along with the event[OnValidating]
. 以及event[OnValidating]
。 I want only the event to be exposed. 我只希望公开该事件。
Also can i allow page to subscribe to event TextboxChanged created inside the usercontrol? 我还可以允许页面订阅在usercontrol内部创建的事件TextboxChanged吗? If so get me the code. 如果是这样,请给我代码。
Note: I would love to see more code than lengthy explanations 注意:我希望看到的代码比冗长的解释更多
You're mixing concepts, you don't need a delegate to register events, try this code, and i'll explain the changes and attempt to answer your questions below 您正在混合概念,不需要委托来注册事件,尝试此代码,我将解释更改并尝试在下面回答您的问题
public event EventHandler Validating;
private void OnValidating(EventArgs ea)
{
var e = Validating;
if (e != null)
e(this, ea);
}
On the page with the control use, notice the On , the framework adds this for all events: 在具有控件用途的页面上,请注意On ,框架将其添加到所有事件中:
<uc:MyUserControl OnValidating="myhandlermethodinpage" />
Couldn't add on comment, but basically if you need custom event args do as such: 无法添加评论,但是基本上,如果您需要自定义事件args,可以这样做:
public event EventHandler<CustomEventArgs> Validating;
private void OnValidating(CustomEventArgs ea)
{
var e = Validating;
if (e != null)
e(this, ea);
}
public class CustomEventArgs:EventArgs{
public int MyProperty { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.