我有一个 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# 中被覆盖,所以我不知道如何解释上述行为......有谁知道这个?