Collection实现INotifyPropertyChang

Collection实现INotifyPropertyChang

本文介绍了使用ObservableCollection实现INotifyPropertyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据库中提取数据以显示到ComboBox中,然后允许用户从该ComboBox中选择值并将它们添加到ListBox中(通过添加/删除按钮).我可以使用ObservableCollections来保存数据库值以绑定到ComboBox,因为它实现了INotifyPropertyChanged(和CollectionChanged)吗?抱歉,如果这是一个基本问题,我大约一个月前开始学习WPF.

I want to pull data from a database to display into a ComboBox, and then allow users to select values from that ComboBox and add them into a ListBox (via add/remove buttons). Would I be able to get away with using an ObservableCollections to hold the database values to bind to the ComboBox, since it implements INotifyPropertyChanged (and CollectionChanged)? Sorry if this is a basic question, I starting learning WPF about a month ago.

我已经阅读了文章(做得很好),萨莎·巴伯(Sacha Barber).

I've read over the article (very well done) by Sacha Barber.

我已经查看了 ObservableCollection .

And I've looked over the MSDN page on ObservableCollection.

使用ObservableCollectionList(我知道没有实现INotifyPropertyChanged)的优点/缺点是什么?

What would be the advantages/disadvantages of using an ObservableCollection vs a List (which I know does not implement INotifyPropertyChanged)?

推荐答案

如果组合框中的项目没有更改(即您没有添加/删除/更新项目),则List对于如果您在影响时手动通知您List属性已更改,您的需求(ObservableCollection也会如此).

If the items in your combobox don't change (i.e. you don't add/remove/update items), then List will probably be OK for your needs (ObservableCollection will be too) if you manually notify that your List property changed when you affect it.

public List<X> MyList
{
    get
    {
        ...
    }

    set
    {
        if (... != value)
        {
            ... = value;
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("MyList"));
            }
        }
    }
}

....

this.MyList = new List<X> { new X(...), new X(...) };

如果您打算在组合框中添加/删除或更新项目(不创建新的MyList对象,即使用this.MyList.Add(...)),则使用ObservableCollection能够通知集合何时更新(因此它可以更新绑定.)

If you plan to add/remove or update items in your combobox (without creating a new MyList object, i.e. using this.MyList.Add(...)), then use ObservableCollection that is able to notify when the collection is updated (so it can update bindings).

这篇关于使用ObservableCollection实现INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!