C#中在多個地方調用同一個觸發器從而觸發同一個自定義委託的事件

場景

在Winfom中能夠在頁面上多個按鈕或者右鍵的點擊事件中觸發同一個自定義的委託事件。工具

實現

在位置一按鈕點擊事件中觸發this

string parentPath = System.IO.Directory.GetParent("指定路徑").ToString();
//獲取指定路徑的父級目錄並做爲參數調用工具類的方法
DataTreeListHelper.TaskView(parentPath);


在位置二右鍵點擊觸發spa

將自定義右鍵的方法定義在上面的工具類中,在工具類中直接調用觸發的方法code

  

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);
                                
                            };

 

在工具類中的觸發的方法中orm

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]);
            }

 

進行邏輯的判斷和觸發blog

在觸發器中觸發事件事件

public static void TriggerTaskView(string taskPath)
        {
            if (OnTaskView != null)
            {
                OnTaskView(taskPath);
            }
        }

 

在當前工具類中自頂義委託和事件get

public delegate void TaskViewDelegete(string taskPath);
public static event TaskViewDelegete OnTaskView;

 

再要執行事件的窗體的構造方法中進行事件的訂閱string

public FrmTaskView()
        {
            InitializeComponent();
            DataTreeListHelper.OnTaskView -= DataTreeListHelper_OnTaskView;
            DataTreeListHelper.OnTaskView += DataTreeListHelper_OnTaskView;
        }

 

編寫具體實現的業務邏輯it

 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;
        }
相關文章
相關標籤/搜索