WPF: Routed events or regular events?

若如初见. 提交于 2020-01-14 07:30:35

问题


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


回答1:


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.

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.

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:

  • 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.

Source: MSDN: Routed Events Overview




回答2:


In WPF control composition is highly used. which mandates to use Routed event, because composition of set of controls exposes single activity most of the time.



来源:https://stackoverflow.com/questions/816392/wpf-routed-events-or-regular-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!