添加项目时,ObservableCollection setter 不会触发 [英] ObservableCollection setter isn't firing when item is added
问题描述
我正在使用 MVVM Light 框架在 WPF 中处理一个项目.我有一个 DataGrid
绑定到一个 ObservableCollection
.到目前为止,当我添加一个新项目时,DataGrid
不会更新,我相信这是因为 setter 永远不会触发.
I am working on a project in WPF using the MVVM Light framework. I have a DataGrid
that is bound to an ObservableCollection<Worker>
. As of now, when I add a new item, the DataGrid
doesn't update and I believe it is because the setter never fires.
public ObservableCollection<Worker> MasterWorkerList
{
get { return _masterWorkerList; }
set
{
System.Windows.MessageBox.Show("Firing");
_masterWorkerList = value;
RaisePropertyChanged(() => MasterWorkerList);
}
}
消息框永远不会显示,即使我调用它:
The messagebox never displays, even when I call this:
DataManager.Data.MasterWorkerList.Add(_create.NewWorker());
如何让 RaisePropertyChanged
触发以便更新 UI?
How can I get RaisePropertyChanged
to fire so I can update the UI?
我尝试使用这篇文章中的解决方案但无济于事:ObservableCollection 没有注意到其中的 Item 何时发生变化(即使使用 INotifyPropertyChanged)
I've tried using the solutions in this post to no avail: ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)
任何建议将不胜感激.如果您需要我的更多代码,请告诉我.
Any advice would be appreciated. If you need more of my code, please let me know.
推荐答案
您不应该在对象的列表上使用公共设置器.你应该在你的构造函数中设置
You shouldn't have public setters on lists for your objects. You should rather set ut up in your constructor
public MyClass(){
_masterWorkerList = new ObservableCollection<Worker>();
_masterWorkerList.CollectionChanged += OnCollectionChanged;
}
public ObservableCollection<Worker> MasterWorkerList
{
get { return _masterWorkerList; }
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){
System.Windows.MessageBox.Show("Firing");
//RaisePropertyChanged(() => MasterWorkerList);
}
CollectionChanged
事件在您 Add
到 ObservableCollection 时被调用.如果您需要更多根深蒂固的控制,您可以从 ObservableCollection
继承并覆盖 AddItem
和 RemoveItem
方法.
The CollectionChanged
event is called when you Add
something to the ObservableCollection. If you need more ingrained control you can inherit from the ObservableCollection
and override the AddItem
and RemoveItem
methods.
这篇关于添加项目时,ObservableCollection setter 不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!