Example implementation of weak events using .NET's WeakEventManager

后端 未结 2 1770
时光取名叫无心
时光取名叫无心 2021-02-04 00:24

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 documentati

2条回答
  •  情书的邮戳
    2021-02-04 00:45

    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);
        }
    
        public static void RemoveListener(PropertyValue source, IWeakEventListener listener)
        {
            CurrentManager.ProtectedRemoveListener(source, listener);
        }
    
        protected override void StartListening(object source)
        {
            ((PropertyValue)source).Changed += DeliverEvent;
        }
    
        protected override void StopListening(object source)
        {
            ((PropertyValue)source).Changed -= DeliverEvent;
        }
    }
    

提交回复
热议问题