Why do WebControl events have the prefix of “On”?

百般思念 提交于 2020-01-02 03:43:07

问题


I'm trying to fully understand the WebForm event model (not the page lifecycle, but how the events are wired up when specified declaratively in the .aspx or .ascx files.

Take the Button control for example. It has a Click event that you can wire to in the code-behind, but it has an "OnClick" event in the .aspx/.ascx file.

I used the .NET Reflector and the Button control has a PROTECTED OnClick method, but that shouldn't be available to be assigned by the .aspx/.ascx. Unless I'm missing something.

Does anyone know why the "On" prefix is added?

Just to clarify a bit: I understand the naming convention works. I'd like to know how the "OnClick" in the .aspx/.ascx gets translated into .Click += new EventHandler(blahName); I.e. if I create a ControlChanged EventHandler, do I need to do anything special to get the OnControlChanged to show up validly in the .aspx/.ascx file?


回答1:


It's more than a naming convention because events in user controls automatically get the "On" prefix in the declarative syntax.

For example, I have a UserControl that declares a ProjectSelected event. To add a handler declaratively, I set the OnProjectSelected attribute.

UserControl:

        public event EventHandler<ProjectSelectedEventArgs> ProjectSelected;

Adding handler declaratively:

        <user:ProjectList id="uxProjectList" runat="server"
            OnProjectSelected="uxProjectList_ProjectSelected" />

Adding handler in code behind:

        uxProjectList.ProjectSelected += uxProjectList_ProjectSelected;

This confused the hell out of me twice, once when I couldn't figure out why the event wasn't available declaratively, and again when I named the event "OnProjectSelected" and the attribute became "OnOnProjectSelected".




回答2:


Those store references to the delegates that the calling code will be wiring up using events; in order to distinguish between the event itself, and the delegate.




回答3:


It's just a naming convention used when raising events. OnSomethingHappened ... OnClick, OnChange, OnClose. I don't think there is anything magical or sinister, it's just a convention.




回答4:


Semantically it is basically an old throwback to VB traditions where event listeners were generally called OnWhatever. Old habits die hard.



来源:https://stackoverflow.com/questions/1004556/why-do-webcontrol-events-have-the-prefix-of-on

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