When Clearing an ObservableCollection, There are No Items in e.OldItems

前端 未结 20 1777
不知归路
不知归路 2020-11-30 00:27

I have something here that is really catching me off guard.

I have an ObservableCollection of T that is filled with items. I also have an event handler attached to t

20条回答
  •  既然无缘
    2020-11-30 01:04

    For the scenario of attaching and detaching event handlers to the elements of the ObservableCollection there is also a "client-side" solution. In the event handling code you can check if the sender is in the ObservableCollection using the Contains method. Pro: you can work with any existing ObservableCollection. Cons: the Contains method runs with O(n) where n is the number of elements in the ObservableCollection. So this is a solution for small ObservableCollections.

    Another "client-side" solution is to use an event handler in the middle. Just register all events to the event handler in the middle. This event handler in turn notifies the real event handler trough a callback or an event. If a Reset action occurs remove the callback or event create a new event handler in the middle and forget about the old one. This approach also works for big ObservableCollections. I used this for the PropertyChanged event (see code below).

        /// 
        /// Helper class that allows to "detach" all current Eventhandlers by setting
        /// DelegateHandler to null.
        /// 
        public class PropertyChangedDelegator
        {
            /// 
            /// Callback to the real event handling code.
            /// 
            public PropertyChangedEventHandler DelegateHandler;
            /// 
            /// Eventhandler that is registered by the elements.
            /// 
            /// the element that has been changed.
            /// the event arguments
            public void PropertyChangedHandler(Object sender, PropertyChangedEventArgs e)
            {
                if (DelegateHandler != null)
                {
                    DelegateHandler(sender, e);
                }
                else
                {
                    INotifyPropertyChanged s = sender as INotifyPropertyChanged;
                    if (s != null)
                        s.PropertyChanged -= PropertyChangedHandler;
                }   
            }
        }
    

提交回复
热议问题