带有自定义参数的 EventHandler

EventHandler with custom arguments(带有自定义参数的 EventHandler)
本文介绍了带有自定义参数的 EventHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Google 上找了大约一个小时的答案,但没有找到我想要的答案.

I've been looking for an answer for about an hour on Google but I did not found exactly what I'm looking for.

基本上,我有一个静态 Helper 类,可以帮助执行我在应用程序中经常做的许多事情.在这种情况下,我有一个名为CreateDataContextMenu"的方法,它在给定的 TreeView 控件上创建上下文菜单.

Basically, I have a static Helper class that helps perform many things I do frequently in my App. In this case, I have a method named "CreateDataContextMenu" that creates a context menu on a given TreeView control.

public static void CreateDataContextMenu(Form parent, TreeView owner, string dataType)
{ ... }

TreeView 所有者是我将关联上下文菜单的控件.

TreeView owner is the control in which I will associate my context menu.

稍后我将 Click 事件添加到 MenuItem,如下所示:

Then later on I add a Click event to a MenuItem like this:

menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click);

我在这里遇到的问题是我想将所有者"和数据类型"作为参数传递给 menuItemFolder_Click 事件.

The problem I have here is that I want to pass "owner" and "dataType" as arguments to the menuItemFolder_Click event.

我尝试了以下方法:

menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click(sender,e,owner,dataType));
(...)
private static void menuItemFolder_Click(object sender, System.EventArgs e, Treeview owner, string dataType)
{...}

但它根本不起作用.这样做可能太天真了,但我对事件处理程序还不是很满意.

But it doesn't work at all. It might be very naive of me to do it that way but I"m not very comfortable with event handler yet.

知道我该怎么做吗?我的第一个猜测是我需要为这种特定情况创建自己的 EventHandler.我是否朝着正确的方向前进?

Any idea on how I could do that? My first guess is that I need to create my own EventHandler for this specific case. Am I going in the right direction with that?

推荐答案

你应该创建一个 lambda 表达式 调用带有额外参数的方法:

You should create a lambda expression that calls a method with the extra parameters:

menuItemFolder.Click += (sender, e) => YourMethod(owner, dataType);

这篇关于带有自定义参数的 EventHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)