65.9K
CodeProject 正在变化。 阅读更多。
Home

Silverlight 中的 List、ObservableCollection 和 INotifyPropertyChanged 对比

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (87投票s)

2009 年 9 月 22 日

CC (ASA 2.5)

2分钟阅读

viewsIcon

378470

downloadIcon

5701

本文主要介绍 List、ObservableCollection 和 INotifyPropertyChanged 的基本概念。

引言

本文介绍 `List`、`ObservableCollection` 和 `INotifyPropertyChanged` 之间的基本理解。

List<T>、ObservableCollection<T> 和 INotifyPropertyChanged 的区别

List<T>

它表示可以通过索引访问的强类型对象列表。 它提供搜索、排序和操作列表的方法。 `List<T>` 类是 `ArrayList` 类的泛型等效类。 它使用一个数组来实现 `IList<T>` 泛型接口,该数组的大小根据需要动态增加。

缺点

在 ASP.NET 中,我们只需使用 `DataSource` 和 `DataBind()` 即可绑定数据,但在 Silverlight 中略有不同。 ASP.NET 中的数据绑定以无状态的方式完成 - 一旦绑定操作完成,就完成了,如果你想改变任何东西,你必须操纵作为数据绑定结果创建的底层控件,或者改变底层数据对象并再次调用 `DataBind()`。 这就是我们习惯的——但这不是一个好的做法。

listgrid.JPG

在示例应用程序中,列表中的值在运行时在代码隐藏中被添加、删除和更改。 列表中的更改将不会更新到 UI(`Datagrid`)。

ObservableCollection<T>

`ObservableCollection` 是一个泛型动态数据集合,当项目被添加、删除或整个集合被刷新时,它会提供通知(使用接口“`INotifyCollectionChanged`”)。

注意:Silverlight 中的 WCF 服务代理类默认会使用这种类型的集合。

observablecollection.JPG

缺点

当集合中的任何属性发生更改时,它不会提供任何通知。

observablecollectiongrid.JPG

在示例应用程序中,observable collection 中的值在运行时在代码隐藏中被添加、删除和更改。 observable collection 中的操作(添加和删除项目)将被更新到 UI(`Datagrid`)。 但是对现有项目的任何更改都不会更新到 UI。

INotifyPropertyChanged

`INotifyPropertyChanged` 不是一个集合,它是一个数据对象类中使用的接口,当任何属性值发生更改时,向客户端提供 `PropertyChanged` 通知。 这将允许你在对象的状态发生更改(添加、删除和修改)时引发 `PropertyChanged` 事件,以通知底层集合或容器状态已更改。

inotifypropertychanged.JPG

inotifypropertychangedgrid.JPG

`INotifyPropertyChanged` 与所有类型的集合兼容,例如 `List<T>`、`ObservableCollection<T>` 等。使用 `INotifyPropertyChanged` 的代码片段如下所示

public class UserNPC:INotifyPropertyChanged
{
    private string name;
    public string Name { 
        get { return name; } 
        set { name = value; onPropertyChanged(this, "Name"); } 
    }
    public int grade;
    public int Grade { 
        get { return grade; } 
        set { grade = value; onPropertyChanged(this, "Grade"); } 
    }

    // Declare the PropertyChanged event
    public event PropertyChangedEventHandler PropertyChanged;

    // OnPropertyChanged will raise the PropertyChanged event passing the
    // source property that is being updated.
    private void onPropertyChanged(object sender, string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
        }
    }
}

在上面的代码片段中,每当将值设置为属性时,将调用方法“`onPropertyChanged`”,该方法反过来会引发 `PropertyChanged` 事件。

历史

  • 2009 年 9 月 22 日:首次发布
© . All rights reserved.