添加项目时,ObservableCollection setter不会触发 [英] ObservableCollection setter isn't firing when item is added
问题描述
我正在使用MVVM Light框架在WPF中进行项目.我有一个绑定到ObservableCollection<Worker>
的DataGrid
.到目前为止,当我添加新项目时,DataGrid
不会更新,我相信这是因为设置程序从不触发.
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
以便更新用户界面?
How can I get RaisePropertyChanged
to fire so I can update the UI?
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.
推荐答案
您不应在对象列表上使用公共设置器.您应该在构造函数中设置ut
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);
}
将Add
内容添加到ObservableCollection时,将调用CollectionChanged
事件.如果您需要更多根深蒂固的控件,则可以从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屋!