使用WPF 4.5通用弱事件管理器处理路由事件? [英] using WPF 4.5 Generic Weak Event Manager for Handled Routed Events?

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

问题描述

我想知道如何将处理的" RoutedEvent的订阅转换为WeakEventManager?

I would like to know how to convert the subscription of "Handled" RoutedEvents to WeakEventManager?

UIElement具有以下方法来订阅处理的" RoutedEvent:UIElement.AddHandler(RoutedEvent routedEvent,委托处理程序,bool handleEventsToo)

UIElement has the following method to subscribe to "Handled" RoutedEvents: UIElement.AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo)

那么我该如何将其转换为通用WeakEventManager表单?

So how do I convert it the the Generic WeakEventManager form?

推荐答案

您应该能够按照创建自定义事件管理器的指南进行操作

You should be able to just follow the guide for creating a custom event manager from MSDN, and implement StartListening and StopListening like this:

protected override void StartListening(object source) {
    var sourceElement = (UIElement)source;
    sourceElement.AddHandler(RoutedEvent, OnRoutedEvent, true);
}

protected override void StopListening(object source) {
    var sourceElement = (UIElement)source;
    sourceElement.RemoveHandler(RoutedEvent, OnRoutedEvent, true);
}

我认为使用通用的WeakEventManager对此没有多大意义,因为它使用事件名称并调用 Type.GetEvent ,当您使用RoutedEvents和AddHandler而不是真实"事件时,这根本没有用.但是,您也许可以编写自己的通用基类来使用RoutedEvents.

I don't think it would make much sense to use the generic WeakEventManager for this, because it uses an event name and calls Type.GetEvent internally, which isn't useful at all when you're using RoutedEvents and AddHandler instead of "real" events. However, you may be able to write your own generic base class for working with RoutedEvents.

我个人使用基于

Personally, I use my own weak event solution based on Dustin Campbell's WeakEventHandler. The nice thing about it is that instead of managing adding and removing internally, it gives you a "weak" version of the original delegate which you can pass around freely... so there is no need to customize the weak event manager's implementation when adding delegates in a different way, because the usage is the same in both cases:

uielement.MouseDown += weakMouseDownHandler;

uielement.AddHandler(UIElement.MouseDownEvent, weakMouseDownHandler, true);

这篇关于使用WPF 4.5通用弱事件管理器处理路由事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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