Organizing Event Handlers Methods
I use asp.net and c# in web forms.
Using Visual Studio it creates automatically Event Handlers Methods for my controls.
VS generate the Method name in this开发者_如何学JAVA way idControl_event
. I know I can give any name to Event Handlers Methods.
So I'm wondering what is your favorite approach at naming theme.
I would like to know if using Web Forms is possible to write Event Handlers Method in a separate class (not in code behind for a specific web page) and how to call theme from the Control.
Thanks for your time.
For event handler names, I generally use the format that Visual Studio generates by default: [idControl]_[eventName]. But that is very much a personal/team preference. I've seen similar discussions about this such as this one or this one. Regardless of how you choose to name the event handlers, I think the most important thing is to remain consistent.
As for having the event handlers outside of your code behind, I haven't seen this done very often but it is possible. The easiest way would be to have a static method in the separate class with the common event handling logic. For example, here is how you could have standard logic for Page.Loaded in a separate class. I believe you'll need to register the event handler via code - I don't think you can do it in markup (aspx).
public static class CommonEventHandlers
{
public static void Page_Loaded(object sender, EventArgs e)
{
//Do any standard logic
//If you need a reference to the page that raised the event,
// you can get it from the 'sender' parameter.
Page page = (Page)sender;
//Do something with 'page'
}
}
Then in the code-behind of the page that you want to use that common event handler:
public partial class WebForm1 : System.Web.UI.Page
{
public WebForm1()
{
//Register the handler via code in the constructor
Load += CommonEventHandlers.Page_Loaded;
}
}
As another option, you could use inheritance to help with code reuse. For example, you could have a base class that your Pages inherit from that has standard handlers. One benefit of this is that you can register event handlers in markup even if the method is declared in a base class so you don't need to do anything in the code-behind of the ancestor page.
I don't think you can have the event handlers in another class, best you could get would probably be inside a separate partial class file
As @Daniel Powell said, I'm pretty sure the best you can do with events is to have them in a different file as a partial class for your code-behind.
Regarding the naming convention, 95% of the time I see events named like you said - idControl_event
. That's the way I name them, as it makes it easy to tie the code to the control when I'm looking at the source.
精彩评论