【问题标题】:Passing an Event and a delegate event handler into a generic Helper Method将 Event 和委托事件处理程序传递到通用 Helper 方法
【发布时间】:2011-11-05 18:46:03
【问题描述】:

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

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

【问题讨论】:

  • 完全摆脱这个 UIThreadExecutor ,订阅事件可以在工作线程上完成。虽然这样做非常不寻常,但很难理解为什么需要这样做。
  • 这不太对 - assigning buttonControl.Click event to the event handler ButtonClickHandler,分配给事件的事件处理程序不是相反的

标签: c# events delegates


【解决方案1】:

关键字:MulticastDelegate

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

当然你也可以使用带有事件声明的接口。

编辑 2:

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

【讨论】:

  • 感谢您的回复和链接。我想我了解 MulticastDelegate。您可以在其中将多个方法分配给单个委托。当您调用单个委托时,每个方法都会被执行。但我不确定如何使用它来拥有作为参数的通用方法 - 对象的事件和事件处理程序方法。然后我必须使用那个 UIThreadExecutor 类 - 将它们连接在一起。 UIThreadExecutor 类是提供给我的,我必须使用它。如果您能指出我正确的方向,将不胜感激。非常感谢。
  • 嗨@Felix K。谢谢你的帖子。不幸的是,我得到一个编译错误:Cannot use ref or out parameter 'eventToSubscribeTo' inside an anonymous method, lambda expression, or query expression。
  • 已更新,这是我能提供的最佳解决方案。
  • 感谢您的帮助和链接 Felix K。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多