如何以编程方式发起活动 [英] How to raise an event Programmatically

查看:91
本文介绍了如何以编程方式发起活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮:

Hi I have a Push button:

void grdctrl_Grid_Prop_PushButtonClick(object sender, GridCellPushButtonClickEventArgs e)
{
}


我需要按下按钮时从其他控件中调用其他事件.该事件的方法是:


and I need some other event from other controls to be called upon pressing the push button. The method for that event is:

private void Hidden_drgdrp_Prop_DragDrop(object sender, DragEventArgs e)
        {
        }
        }


这些控件都不是标准控件,它们都是用户控件(但黑框,其来源均未使用).
因此,我正在寻找一种方法来以编程方式在我的按钮click方法中引发事件(并因此引发 Hidden_​​drgdrp_Prop_DragDrop 方法).


None of these controls are the standard controls, and both are the user controls(but black box, no acess to their source).
So, I am looking for a way to raise an event(and consequently Hidden_drgdrp_Prop_DragDrop method) programmitically in my pushbutton click method.
Is their a general method to raise any event(with different EventArgs)Programmatically?

推荐答案

我在代码项目中有2个解决方案,可以通过编程方式引发事件,
以编程方式引发事件 [如何以编程方式调用单击列标题"事件? [
i got 2 solutions in code project for raising an event Programmatically,
raising an event programmatically[^]
How to call "click on column header" event programmatically?[^]


尝试Hidden_drgdrp_Prop_DragDrop(sender,new DragEventArgs() );


以阐明其他答案:

与直接使用的委托实例相比,事件对象有许多限制.一个重要的限制是:只有一种方法可以调用事件:在声明事件实例的类的代码中.无论访问修饰符还是其他任何东西,都不可能从其他任何地方调用事件,甚至不能从派生类,同一类的不同实例调用事件.只是不允许这样做.

此限制不适用于直接使用的常规委托实例,但是从其他类或其他实例通过直接访问委托实例来这样做将是不好的编程习惯.也就是说,事件限制是有充分理由设计的,是一项重要的防呆措施.

因此,您甚至不应尝试找到任何解决方法来在其声明类及其实例之外调用事件,也不要尝试通过委托实例应用等效技术.相反,您应该提高逻辑性".您应该创建一个单独的方法以在程序的两个或多个位置使用:一个位置是事件处理程序的调用,另一个是从其他地方的调用.

—SA
In clarification of other answers:

The event objects have a number of limitations compared to delegate instances used directly. One important limitation is: there is only one way to invoke an event: in the code of the class where the event instance is declared. It is not possible to invoke a event from anywhere else, not even from a derived class, not from a different instance of the same class, regardless to access modifiers or anything else. This is just not allowed.

This limitation does not apply to regular delegate instances used directly, but doing so from other classes or different instances through direct access to a delegate instance would be bad programming practice. That said, this limitation for event is designed for a good reason, as an important fool-proof measure.

By this reason, you should not even try to find any work-around to invoke an event outside its declaring class and its instance, and not try to apply equivalent technique through delegate instances. Instead, you should "move you logic". You should create a separate method to be used in two or more places of you program: one place is a call from the event handler, another one — from somewhere else.

—SA


这篇关于如何以编程方式发起活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆