c# - 将事件和委托(delegate)事件处理程序传递到通用帮助程序方法中

标签 c# events delegates

我的代码中都有这些。这是一个 WP7 Silverlight 应用程序。

UIThreadExecutor.UIThreadExec.Execute(() => buttonControl.Click += 
                                new RoutedEventHandler(this.ButtonClickHandler));

因此,上面的代码在 UI 线程上将 buttonControl.Click 事件分配给事件处理程序 ButtonClickHandler .. 例如:

public void ButtonClickHandler(object sender, System.Windows.RoutedEventArgs e)
{

}

我想要的是重构:

UIThreadExecutor.UIThreadExec.Execute(() => buttonControl.Click += 
                                new RoutedEventHandler(this.ButtonClickHandler));

到一个静态但通用的帮助器方法中——能够指定任何 UI 控件事件和事件处理程序。然后该方法将使用 UIThreadExecutor 类将两者连接在一起。

当然,buttonControl 也可以是任何 UI 控件 - 具有相同类型的不同事件。例如 - 它可以是带有 Checked 事件的 RadioButton。

如果我转到 VS 2010 中 RadioButton.Checked 或 Button.Click 的定义,它们都是同一类型:

public event RoutedEventHandler Checked;

我一直在为这个问题挠头。我想过,在我的静态助手中 - 声明一个委托(delegate)(在命名空间级别声明):

public delegate void UIControlHandler(object sender, RoutedEventArgs e);

然后我的辅助方法如下所示:

public static void SubscribeToUIEvent(EventHandler eventToSubscribeTo, 
                                                        UIControlHandler handler)
{
    UIThreadExecutor.UIThreadExec.Execute(() => eventToSubscribeTo += handler);
}

出现编译错误:

Operator '+=' cannot be applied to operands of type 'System.EventHandler' and UIControlHandler
Cannot implicitly convert type UIControlHandler' to 'System.EventHandler'

谁能帮我指明正确的方向?这让我发疯。

最佳答案

关键字:MulticastDelegate

这里是关于 C# 中的事件/委托(delegate)的一般概述。 http://www.codeproject.com/KB/cs/delegates_overview.aspx

当然,您也可以使用带有事件声明的接口(interface)。

编辑 2:

我找到了这个:How to pass an event to a method? 这应该会有所帮助,我认为您不会得到更好的解决方案,因为无法将 ref 参数传递给匿名方法。

关于c# - 将事件和委托(delegate)事件处理程序传递到通用帮助程序方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8022406/

相关文章:

c# - 为什么我在定义自定义配置文件时收到 TypeLoadException?

ios - appDelegate 引用

c# - 将数组的一部分复制到另一个数组中

c# - 在 Windows 8 Metro (WinRT) 和 C#/XAML 中,实现流动项目结果(即连续分页)的最佳实践是什么?

javascript - d3js mousemove事件不冒泡

c++ - 如何在 C/C++ 中创建自己的事件?

javascript - mouseover 有时会触发而不是 touchstart - 为什么?

wpf - 创建依赖属性以在 XAML 中设置自定义事件处理程序

c# - 如何使作为 SWIG shared_ptr 传递给非托管代码的托管代码对象保持事件状态?

c# - 如何自动将生成的源文件包含到 Visual Studio 中的 C# 项目中?