简体   繁体   English

如何从另一个处理程序调用/调用按钮单击事件处理程序? (C# )

[英]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. 我一定缺少明显的东西-我是.NET的新手-多年来一直在C ++ / MFC中开发。

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 这是在紧凑的框架中/ Win Mobile

You need to do one of the following: 您需要执行以下操作之一:

  • Provide access to the handler's containing class instance (ie 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. 在事件处理程序1内,只需引发事件处理程序2正在为其“监听”的事件即可。 So inside event handler 1, put OnEvent() . 因此,在事件处理程序1中,放入OnEvent() Note that event handler 2 must have already been hooked up to listen to the event. 请注意,事件处理程序2必须已经挂接到监听事件。

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. 这是一个很容易解决的问题-我只是使处理程序对于处理第二个事件的对象/窗体可见,因此很容易触发另一个事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM