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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With