0

我有一个 ObservableCollection,我需要通过重新加载按钮来替换它。在尝试这个过程中,我发现即使变量“myCollection”在“ReLoadData”中被取消(参见下面的代码示例)并分配了一个新的 ObservableCollection,但我没有向其 CollectionChanged 成员添加任何事件处理程序,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# 中被覆盖,所以我不知道如何解释上述行为......有谁知道这个?

4

1 回答 1

0

(来自评论)

我怀疑谁在“填充”收藏 - 仍然与旧的“收藏”有关

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

于 2013-03-31T19:48:11.350 回答