c#从另一个类中的另一个静态事件引发事件 [英] c# raise event from another static event in another class

查看:226
本文介绍了c#从另一个类中的另一个静态事件引发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要另一个类的帮助调用事件. 我有宣告事件的课程:

Need help calling event from another class. I have class with declared event:

     public class MxPBaseGridView : GridView
    {

        public event AddNewItemsToPopUpMenuEventHandler AddNewItemsToPopUpMenu;
          ...
    }

我需要从中调用事件的另一个类具有方法和"AddNewItemsToPopUpMenuEventHandler"委托

Another class from which i need to call event has methods and "AddNewItemsToPopUpMenuEventHandler " delegate

    public delegate void AddNewItemsToPopUpMenuEventHandler(PopupMenuShowingEventArgs e);
    public static class GridViewUtils
{
public static void gridView_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
    {                     
        if (e.MenuType != DevExpress.XtraGrid.Views.Grid.GridMenuType.Row)
        {
           if (menu != null)
            {               
                if (sender is MxPBaseAdvBandedGridView)
                {
                    MxPBaseAdvBandedGridView currentGrid = sender as MxPBaseAdvBandedGridView;

...

                    currentGrid.AddNewItemsToPopUpMenu();
                    if (currentGrid.AddNewItemsToPopUpMenu != null) //there i need to call event
                        currentGrid.AddNewItemsToPopUpMenu(e); // how you understand it doesn't work 
                }

那么做同样工作的正确方法是什么?

so what is the right way to do the same job?

推荐答案

您只能在已定义事件的类中调用事件.常见的是使用特定的方法来触发事件,您必须在定义事件的类中添加该方法.对于您的情况,在类MxPBaseGridView中.添加以下内容:

You can only invoke an event in the class where you have defined the event. What is common is to use a specific method to fire the event, which you have to add in the class where you define the event. In your case, in the class MxPBaseGridView. Add the following:

public void OnAddNewItemsToPopUpMenu(<eventargstype> e) {
    var addNewItemsToPopUpMenu = AddNewItemsToPopUpMenu;
    if (addNewItemsToPopUpMenu != null)
        addNewItemsToPopUpMenu(this, e);
}

注意:我不确定eventargs-type是什么,所以我将其保持打开状态.

Note: I'm not sure what the eventargs-type is, so I've left it open.

然后您可以从静态方法中调用此方法.

Then you can call this method from your static method.

注意:通常,我将On ...方法定义为私有方法,如果需要的话,将其定义为受保护的方法.在这种情况下,我将其定义为公共,因为您需要从班级外部调用它.

Note: normally I define the On... methods as private, if necessary as protected. In this case I've defined it public since you need to call it from outside your class.

这篇关于c#从另一个类中的另一个静态事件引发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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