I have an ObservableCollection which I need to replace via a reload button. During trying this out I found out that the CollectionChanged event fires even though the variable "myCollection" was nullified in "ReLoadData" (see code example below) and assigned a new ObservableCollection where I did not add any event handler to its CollectionChanged member:
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");
}
}
I suspect this may have something to do with how the assignment operator is implemented in C#, but as far as I read it can not be overridden in C#, so I have no clue how to explain the above behaviour... Does anyone know this?