场景
在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;
}