添加项目时,ObservableCollection setter不会触发 [英] ObservableCollection setter isn't firing when item is added

查看:123
本文介绍了添加项目时,ObservableCollection setter不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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继承并覆盖AddItemRemoveItem方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆