简体   繁体   English

WeakEventManager 和 DependencyPropertyChangedEventArgs

[英]WeakEventManager & DependencyPropertyChangedEventArgs

I am wondering what might be the best way to use the WeakEventManager (4.5 is fine) together with Events offerring DependencyPropertyChangedEventArgs.我想知道将 WeakEventManager(4.5 很好)与提供 DependencyPropertyChangedEventArgs 的事件一起使用的最佳方法是什么。 These do not derive from EventArgs (for performance reasons) and therefore WeakEventManager does not work out of the Box.这些不是从 EventArgs 派生的(出于性能原因),因此 WeakEventManager 不能开箱即用。

Any guides, links or tips would be highly appreciated!任何指南、链接或提示将不胜感激!

使用 .NET 内置的PropertyChangedEventManager

I'm not sure how using 'PropertyChangedEventManager' would resolve the issue regarding 'WeakEventManager' and binding weak event handlers that use 'DependencyPropertyChangedEventArgs'.我不确定使用“PropertyChangedEventManager”如何解决有关“WeakEventManager”和使用“DependencyPropertyChangedEventArgs”的绑定弱事件处理程序的问题。

The 'PropertyChangedEventManager' works with instances of 'PropertyChangedEventArgs', which is derived from 'EventArgs', where 'DependencyPropertyChangedEventArgs' does not. 'PropertyChangedEventManager' 与 'PropertyChangedEventArgs' 的实例一起使用,它派生自 'EventArgs',而 'DependencyPropertyChangedEventArgs' 则没有。 This is why standard methods don't work.这就是标准方法不起作用的原因。

In cases like this you can always use a manual approach ('WeakEventHandler' is declared within the scope of the 'MyType' class):在这种情况下,您始终可以使用手动方法(在“MyType”类的范围内声明“WeakEventHandler”):

private class WeakEventHandler
{
    private readonly System.WeakReference<MyType> m_WeakMyTypeRef;
        
    public WeakEventHandler(MyType myType) => m_WeakMyTypeRef = new System.WeakReference<MyType>(myType);

    public void OnClientIsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        if (m_WeakMyTypeRef.TryGetTarget(out var myType))
            myType.OnClientIsKeyboardFocusWithinChanged(sender, args);
    } 
}

And code to bind (from within 'MyType' method):和要绑定的代码(从“MyType”方法中):

var weakEventHandler = new WeakEventHandler(this);
frameworkElement.IsKeyboardFocusWithinChanged += weakEventHandler.OnClientIsKeyboardFocusWithinChanged;

The downside is that you have to declare a new (private) class although the same class could handle multiple events.缺点是您必须声明一个新的(私有)类,尽管同一个类可以处理多个事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM