5

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!

Gope
  • 1,672
  • 1
  • 13
  • 19

2 Answers2

2

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.

karmasponge
  • 1,169
  • 2
  • 12
  • 26
1

Use the PropertyChangedEventManager built in to .NET.

Jeff
  • 2,701
  • 2
  • 22
  • 35
  • Looking at the Documentation it appears to be exactly what I was looking for. Thanks a lot! – Gope Jun 02 '14 at 07:43
  • UIElement who has IsVisibleChanged does not implement INotifyPropertyChanged, and can't be used as source object for the event. – bigfoot May 18 '20 at 20:59
  • It's not clear how this answer actually resolves the issue in question. I've added my own answer to clarify. – karmasponge Mar 03 '21 at 02:33
  • This answer does NOT answer this question. The `PropertyChangedEventManager` built in to .NET cannot be used with `DependencyPropertyChangedEventArgs` as that does **not** extend `EventArgs`. – Sheridan Jun 14 '22 at 13:28