views:

78

answers:

1

Is there an example implementation of weak events using .NET's WeakEventManager?

I'm trying to implement it by following the "Notes to Inheritors" in the documentation, but it is vague. For example, I can't figure out how to call ProtectedAddListener from my static AddListener function in my custom manager.

A: 

I figured it out on my own following the guidelines in the "Notes for Inheritors" section of the WeakEventManager documentation. Here's a basic implementation of WeakEventManager. The class sourcing the event is named PropertyValue and the event is named Changed.

public class PropertyValueChangedEventManager : WeakEventManager
{
    public static PropertyValueChangedEventManager CurrentManager
    {
        get
        {
            var manager_type = typeof(PropertyValueChangedEventManager);
            var manager = WeakEventManager.GetCurrentManager(manager_type) as PropertyValueChangedEventManager;

            if (manager == null)
            {
                manager = new PropertyValueChangedEventManager();
                WeakEventManager.SetCurrentManager(manager_type, manager);
            }

            return manager;
        }
    }

    public static void AddListener(PropertyValue source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedAddListener(source, listener);
        return;
    }

    public static void RemoveListener(PropertyValue source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedRemoveListener(source, listener);
        return;
    }

    protected override void StartListening(object source)
    {
        ((PropertyValue)source).Changed += mHandler;
        return;
    }

    protected override void StopListening(object source)
    {
        ((PropertyValue)source).Changed -= mHandler;
        return;
    }

    private EventHandler mHandler = (s, e) =>
    {
        CurrentManager.DeliverEvent(s, e);
        return;
    };
}
emddudley
Microsoft provides PropertyChangedEventManager (http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventmanager.aspx) and CollectionChangedEventManager (http://msdn.microsoft.com/en-us/library/system.collections.specialized.collectionchangedeventmanager.aspx) built-in to .NET.
emddudley