失去的ObservableCollection绑定时I"新"它 [英] ObservableCollection loses binding when I "new" it

查看:154
本文介绍了失去的ObservableCollection绑定时I"新"它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的用户界面的列表框绑定到的ObservableCollection的属性。我设置的ObservableCollection的新实例到视图模型的构造属性,我可以在表单上的按钮添加项目。这些都是在列表中。

I have a ListBox on my UI that is bound to a property of ObservableCollection. I set a new instance of the ObservableCollection into the property in the view model's constructor and I can add items to it with a button on the form. These are visible in the list.

所有这些都是好的。

不过,如果我重新初始化财产的新的的按钮中的回调,它打破了绑定和UI不再显示什么收藏。

However, if I reinitialize the property with new in the button callback, it breaks the binding and the UI no longer shows what is in the collection.

我承担的结合将继续查找属性的值,但它的presumably链接到由摧毁了一个参考的新的

I assumed the binding would continue to look up the values of the property, but its presumably linked to a reference which is destroyed by the new.

我有没有得到这个权利?任何人都可以对这个是怎么联系起来扩大?有没有一种方法重新绑定,当我的视图模型没有视图的知识呢?

Have I got this right? Can anyone expand on how this is linked up? Is there a way to rebind it when my view model has no knowledge of the view?

推荐答案

请确保你提出一个PropertyChangedEvent你reintialize您的收藏之后。提高本次活动将让视图来处理变化与不具有视图的知识模型的属性。

Make sure you are raising a PropertyChangedEvent after you reintialize your collection. Raising this event will allow the view to handle changes to the property with the model having no knowledge of the view.

class Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    private ObservableCollection<string> _list = new ObservableCollection<string>();
    public ObservableCollection<string> List
    {
        get { return _list; }
        set 
        { 
            _list = value;
            NotifyPropertyChanged("List");
        }
    }

    public Model()
    {
        List.Add("why");
        List.Add("not");
        List.Add("these?");
    }
}

这篇关于失去的ObservableCollection绑定时I&QUOT;新&QUOT;它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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