为什么不给ObservableCollection赋值销毁CollectionChanged订阅者列表?

本文关键字:列表 CollectionChanged ObservableCollection 赋值 为什么不 | 更新日期: 2023-09-27 18:06:38

我有一个ObservableCollection,我需要通过一个重新加载按钮来替换。在尝试这个过程中,我发现CollectionChanged事件触发,即使变量"myCollection"在"ReLoadData"中无效(见下面的代码示例),并分配了一个新的ObservableCollection,我没有添加任何事件处理程序到它的CollectionChanged成员:

    public partial class MainWindow : Window
    {
        private ObservableCollection<string> myCollection = 
           new ObservableCollection<string>();
        public MainWindow()
        {
           InitializeComponent();
           myCollection.CollectionChanged += new    
           System.Collections.Specialized.NotifyCollectionChangedEventHandler(
           myCollection_CollectionChanged);
        }
        //Invoked in button click handler:
        private void ReLoadData()
        {
           ObservableCollection<string> newCollection =
              new ObservableCollection<string>();
           //Filling newCollection with stuff...
           //Marks old collection for the garbage collector
           myCollection = null;
           myCollection = newCollection;          
        }
        void myCollection_CollectionChanged(
           object sender,   
           System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
           //Set breakpoint on statement or one of the braces.
        }
        private void AddItem(object sender, RoutedEventArgs args)
        {
           //Why does the following fire CollectionChanged
           //although myCollection was nullified in
           //ReLoadAuctionData() before?
           myCollection.Add("AddedItem");
        }
   }

我怀疑这可能与赋值操作符在c#中的实现方式有关,但据我所知,它不能在c#中被覆盖,所以我不知道如何解释上述行为…有人知道吗?

为什么不给ObservableCollection赋值销毁CollectionChanged订阅者列表?

(来自评论)

我怀疑"填充"集合的人仍然存在连接到旧的'collection'

。不管INotifyCollectionChanged, that's just for inside collection -你仍然需要"通知"任何"订阅者","整个"集合已经改变-并使用INotifyPropertyChanged -即在"废除"(这是不必要的顺便说一句)。you need to call OnPropertyChanged("Collection") or whatever is named .