欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中在多个地方调用同一个触发器从而触发同一个自定义委托的事件

程序员文章站 2022-07-17 08:06:10
场景 在Winfom中可以在页面上多个按钮或者右键的点击事件中触发同一个自定义的委托事件。 实现 在位置一按钮点击事件中触发 string parentPath = System.IO.Directory.GetParent("指定路径").ToString(); //获取指定路径的父级目录并作为参 ......

场景

在winfom中可以在页面上多个按钮或者右键的点击事件中触发同一个自定义的委托事件。

实现

在位置一按钮点击事件中触发

string parentpath = system.io.directory.getparent("指定路径").tostring();
//获取指定路径的父级目录并作为参数调用工具类的方法
datatreelisthelper.taskview(parentpath);


在位置二右键点击触发

将自定义右键的方法定义在上面的工具类中,在工具类中直接调用触发的方法

  

system.windows.forms.menuitem mnutaskview = new system.windows.forms.menuitem();
                            mnutaskview.text = "查看任务";
                            mnutaskview.click += delegate(object s, eventargs ea)
                            {
                                string parentpath  = directory.getparent(stridvalue).tostring();
                                taskview(parentpath);
                                
                            };

 

在工具类中的触发的方法中

public static void taskview(string currentpath)
        { 
            //判断当前路径下是否有任务文件
            list<string> taskfilelist = filehelper.getfilelistwithextend(new directoryinfo(currentpath), "*.pcj");
            if(taskfilelist == null || taskfilelist.count ==0)
            {
                xtramessagebox.show("当前路径下没有任务文件");
            }
            else if (taskfilelist.count > 1)
            {
                xtramessagebox.show("当前路径下含有多个任务文件");
            }
            else 
            {
               frmtaskview taskview = new dialog.frmtaskview();
                taskview.show();
                //触发查看任务事件
                triggertaskview(taskfilelist[0]);
            }

 

进行逻辑的判断和触发

在触发器中触发事件

public static void triggertaskview(string taskpath)
        {
            if (ontaskview != null)
            {
                ontaskview(taskpath);
            }
        }

 

在当前工具类中自顶义委托和事件

public delegate void taskviewdelegete(string taskpath);
public static event taskviewdelegete ontaskview;

 

再要执行事件的窗体的构造方法中进行事件的订阅

public frmtaskview()
        {
            initializecomponent();
            datatreelisthelper.ontaskview -= datatreelisthelper_ontaskview;
            datatreelisthelper.ontaskview += datatreelisthelper_ontaskview;
        }

 

编写具体实现的业务逻辑

 private void datatreelisthelper_ontaskview(string taskpath)
        {
            if (taskpath != null)
            {
                this.taskusercontrol1.initialtaskusercontrol(taskpath);
            }
        }

 

为了以防事件没法解除订阅,在窗口关闭事件中进行事件的取消订阅

private void frmtaskview_formclosing(object sender, formclosingeventargs e)
        {
            datatreelisthelper.ontaskview -= datatreelisthelper_ontaskview;
        }