我有一个ObservableCollection,我需要通过重新加载按钮替换它。在尝试这个过程中,我发现即使变量“myCollection”在“ReLoadData”中无效(参见下面的代码示例)并且分配了一个新的ObservableCollection,我没有向其CollectionChanged成员添加任何事件处理程序,也会触发CollectionChanged事件: / p>
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#中重写,所以我不知道如何解释上述行为...谁知道这个?
答案 0 :(得分:0)
(来自评论)
我怀疑那些'填充'收藏品的人 - 仍然是 连接到旧的'集合'
即。无论INotifyCollectionChanged, that's just for inside collection
如何 - 你仍然需要'通知'任何'订阅者''整个'集合已经改变 - 以及使用INotifyPropertyChanged - 即'anulling'(这是不必要的btw。){{1 }}