ObservableCollection 和 CollectionChanged 事件
为什么下面的代码中没有触发 collectionchanged 事件,但我可以看到添加到 ObservableCollection 中的 InventoryBTO 的新实例?
private ObservableCollection<InventoryBTO> _inventoryRecords;
public ObservableCollection<InventoryBTO> InventoryRecords
{
get { return _inventoryRecords; }
set { _inventoryRecords = value; }
}
private InventoryBTO _selectedRecord;
public InventoryBTO SelectedRecord
{
get { return _selectedRecord; }
set
{
if (_selectedRecord != value)
{
_selectedRecord = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedRecord"));
}
}
}
public InventoryViewModel()
{
if (_inventoryRecords == null)
{
InventoryRecords = new ObservableCollection<InventoryBTO>();
this.InventoryRecords.CollectionChanged += new NotifyCollectionChangedEventHandler(InventoryRecords_CollectionChanged);
}
_inventoryRecords = InventoryListBTO.GetAllInventoryRecords();
}
void InventoryRecords_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}
Why does the collectionchanged event not fire in the following code, yet I can see the new instance of InventoryBTO I add to the ObservableCollection?
private ObservableCollection<InventoryBTO> _inventoryRecords;
public ObservableCollection<InventoryBTO> InventoryRecords
{
get { return _inventoryRecords; }
set { _inventoryRecords = value; }
}
private InventoryBTO _selectedRecord;
public InventoryBTO SelectedRecord
{
get { return _selectedRecord; }
set
{
if (_selectedRecord != value)
{
_selectedRecord = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedRecord"));
}
}
}
public InventoryViewModel()
{
if (_inventoryRecords == null)
{
InventoryRecords = new ObservableCollection<InventoryBTO>();
this.InventoryRecords.CollectionChanged += new NotifyCollectionChangedEventHandler(InventoryRecords_CollectionChanged);
}
_inventoryRecords = InventoryListBTO.GetAllInventoryRecords();
}
void InventoryRecords_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您将私有成员分配给从方法返回的
ObservableCollection
的新实例。因此,发生的情况是,您连接到一个集合的事件,但随后删除该实例并将其替换为您从未连接过事件处理程序的新实例。这是你可以做的。创建一个继承自 ObservableCollection 的类并添加 addrange 方法:然后,您可以将您的类更改为:
The problem is that you're assigning your private member to a new instance of an
ObservableCollection
that you're getting back from your method. Therefore, what's happening is, you're hooking up to the event of one collection, but then blowing away that instance and replacing it with a new instance you never hooked up an event handler to. Here's what you can do. Create a class that inherits fromObservableCollection
and adds an addrange method:Then, you can change your class to this:
尝试这个
或
取决于您的实现。
Try this
OR
Depending on your implementation.