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