How Do I invoke/call a button click event handler form another handler? (c# )
I must be missing something obvious - I am new to .NET - been developing in C++/MFC for years.
In an event handler for a button click I would like to then re-use another event handler/click. However, I can't seem to figure out how to do that.
The bit that may be causing trouble is that the handler for the second item I want to "fire" is not on the same form/context.
It seems that I should just be able to call the method...
But I don't seem to be able to do it.
This is in compact framewor开发者_C百科k/Win Mobile
You need to do one of the following:
- Provide access to the handler's containing class instance (i.e. a reference to that object)
- Make the handler a static so any instance can reference it directly
- Put the handler in some other globally available object (static, singleton, etc) so both consumers can use it
- Use a framework that provides event aggregation so you don't have to worry about such things
How about you factor out the common code into a private method? Then you can call that method from both handlers.
I think a better solution would be to refactor your code so that the work done by the original event handler is contained within a function.
Then both the original handler and the new handler both call the same function.
Inside of event handler 1, just raise the event that event handler 2 is "listening" for. So inside event handler 1, put OnEvent()
. Note that event handler 2 must have already been hooked up to listen to the event.
I can speak in more specificity if you show some more code, but this may be enough.
My ignorance. I just didn't have visibility to the other handler. This is a simple problem to solve - I just made the handler visible to the object/form that handles the second event and it is easy to fire the other event.
精彩评论