How Do I invoke/call a button click event handler form another handler? (c# )

北战南征 提交于 2019-12-10 22:17:25

问题


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 framework/Win Mobile


回答1:


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



回答2:


How about you factor out the common code into a private method? Then you can call that method from both handlers.




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/7433428/how-do-i-invoke-call-a-button-click-event-handler-form-another-handler-c

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