Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WeakEventManager & DependencyPropertyChangedEventArgs

I am wondering what might be the best way to use the WeakEventManager (4.5 is fine) together with Events offerring DependencyPropertyChangedEventArgs. These do not derive from EventArgs (for performance reasons) and therefore WeakEventManager does not work out of the Box.

Any guides, links or tips would be highly appreciated!

like image 806
Gope Avatar asked Oct 22 '22 20:10

Gope


1 Answers

I'm not sure how using 'PropertyChangedEventManager' would resolve the issue regarding 'WeakEventManager' and binding weak event handlers that use 'DependencyPropertyChangedEventArgs'.

The 'PropertyChangedEventManager' works with instances of 'PropertyChangedEventArgs', which is derived from 'EventArgs', where 'DependencyPropertyChangedEventArgs' does not. 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):

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):

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.

like image 181
karmasponge Avatar answered Oct 28 '22 20:10

karmasponge