top-silverlight | Just another WordPress weblog

六/09

4

12.3.1 使用ObservableCollection(1)

  12.3 绑定到集合 

  数据绑定的数据源对象可以是一个含有数据的单一对象,也可以是一个对象的集合。之前,一直在讨论如何将目标对象与一个单一对象绑定。Silverlight中的数据绑定还能将目标对象与集合对象相绑定,这也是很常用的。比如显示文章的题目列表、显示一系列图片等。

  如果要绑定到一个集合类型的数据源对象,绑定目标可以使用ItemsControl,如ListBox或DataGrid等。另外,通过定制ItemsControl的数据模板(DataTemplate),还可以控制集合对象中每一项的显示。

  12.3.1 使用ObservableCollection(1)

  数据源集合对象必须继承IEnumerable接口,为了让目标属性与数据源集合的更新(不但包括元素的修改,还包括元素的增加和删除)保持同步,数据源集合还必须实现INotifyPropertyChanged接口和INotifyCollectionChanged接口。

  在Silverlight中创建数据源集合可以使用内建的ObservableCollection类,因为ObservableCollection类既实现了INotifyPropertyChanged接口,又实现了INotifyCollectionChanged接口。使用ObservableCollection类不但可以实现Add、Remove、Clear和Insert操作,还可以触发PropertyChanged事件。

  下面通过一个实例介绍绑定到集合的具体步骤。

  (1)创建数据源集合对象。

  新建一个Silverlight工程,创建Music类,代码如例程12-9所示。

  例程12-9 数据源集合对象

  using System;usingSystem.ComponentModel;namespaceBindingCollectionSamplepublic classMusic :INotifyPropertyChangedprivate string musicName;publicstringMusicNameget return musicName; setmusicName=value;NotifyPropertyChanged(“MusicName”);

  private string author;public string Authorget returnauthor;setauthor = value;NotifyPropertyChanged(“Author”);

  private TimeSpan length;public TimeSpan Lengthget returnlength;setlength = value;NotifyPropertyChanged(“Length”);

  public event PropertyChangedEventHandler PropertyChanged;

  public Music(string musicName, string author,TimeSpanlength)MusicName = musicName;Author = author;Length =length;

  接着,创建集合类MusicCollection,使其继承自ObservableCollection<Music>,代码如下所示。

  usingSystem.Collections.tModel;namespaceBindingCollectionSamplepublicclassMusicCollection:ObservableCollection<Music>

No tags

No comments yet.

Leave a Reply

<<

>>

Theme Design by devolux.nh2.me