将事件和委托事件处理程序传递给通用帮助程序方法

我的代码中都有这些。 这是一个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; 

我一直在摸不着头脑。 我想到了,在我的静态帮助器中 – 声明一个委托(在命名空间级别声明):

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

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

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

这会出现编译错误:

运算符’+ =’不能应用于’System.EventHandler’和UIControlHandler类型的操作数
无法将类型UIControlHandler’隐式转换为’System.EventHandler’

谁能帮助我指出正确的方向? 这真让我抓狂。

关键字:MulticastDelegate

以下是有关C#中事件/委托的概述。 http://www.codeproject.com/KB/cs/delegates_overview.aspx

当然,您也可以使用带有事件处理的接口。

编辑2:

我发现了这个: 如何将事件传递给方法? 这应该有帮助,我认为你不会得到更好的解决方案,因为不可能将ref params传递给anonymus方法。