WPF:路由事件还是常规事件? [英] WPF: Routed events or regular events?

查看:131
本文介绍了WPF:路由事件还是常规事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,我们已经传送了事件。何时应该使用这些代替常规事件?

In WPF we have routed events. When should these be used instead of regular events?

推荐答案

路由事件有特殊的行为,但是如果你是处理提出元素的事件。

Routed events have special behavior, but that behavior is largely invisible if you are handling an event on the element where it is raised.

如果您使用任何建议的方案,路由事件变得强大:在常见根目录定义常用处理程序,合成自己的控件或定义自己的自定义控件类。

Where routed events become powerful is if you use any of the suggested scenarios: defining common handlers at a common root, compositing your own control, or defining your own custom control class.

路由事件侦听器和路由事件源不需要在其层次结构中共享公共事件。任何 UIElement ContentElement 可以是任何路由事件的事件侦听器。因此,您可以使用整个工作API集中可用的全部路由事件作为概念接口,从而应用程序中的不同元素可以交换事件信息。路由事件的接口概念特别适用于输入事件。

Routed event listeners and routed event sources do not need to share a common event in their hierarchy. Any UIElement or ContentElement can be an event listener for any routed event. Therefore, you can use the full set of routed events available throughout the working API set as a conceptual "interface" whereby disparate elements in the application can exchange event information. This "interface" concept for routed events is particularly applicable for input events.

路由事件也可以用于通过元素树进行通信,因为事件的事件数据永久存在于路由中的每个元素。一个元素可以在事件数据中更改某些内容,并且该更改可用于路由中的下一个元素。

Routed events can also be used to communicate through the element tree, because the event data for the event is perpetuated to each element in the route. One element could change something in the event data, and that change would be available to the next element in the route.

除了路由方面,还有两个其他原因,即任何给定的WPF事件可能被实现为路由事件而不是标准CLR事件。如果您正在实施自己的活动,您也可以考虑以下原则:

Other than the routing aspect, there are two other reasons that any given WPF event might be implemented as a routed event instead of a standard CLR event. If you are implementing your own events, you might also consider these principles:


  • 某些WPF样式和模板功能(例如 EventSetter EventTrigger 需要引用的事件作为路由事件。这是前面提到的事件标识符场景。

  • 路由事件支持类处理机制,由此类可以指定在任何注册的实例处理程序可以访问路由事件之前有机会处理路由事件的静态方法。这在控制设计中非常有用,因为您的类可以强制实施事件驱动的类行为,这些行为不能通过处理实例上的事件而被意外地抑制。

  • Certain WPF styling and templating features such as EventSetter and EventTrigger require the referenced event to be a routed event. This is the event identifier scenario mentioned earlier.
  • Routed events support a class handling mechanism whereby the class can specify static methods that have the opportunity to handle routed events before any registered instance handlers can access them. This is very useful in control design, because your class can enforce event-driven class behaviors that cannot be accidentally suppressed by handling an event on an instance.

资料来源: MSDN:路由事件概述

这篇关于WPF:路由事件还是常规事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆