WPF提供了一个ObservableCollection类,它实现了一个暴露了INotifyPropertyChanged的数据集合。也就是说我们不需要自己对每个单独的数据实现INotifyPropertyChanged结构。我们先看看如何实现一个简单的绑定数据集合。
代码很简单,基本上就是这样的一个模板。然后,我们就可以把LYLDataObjCol绑定到一个需要多项数据的Element之上,比如ListBox、ComboBox等等。namespace NSLYL { public class LYLDataObj { public LYLDataObj(string name, string description) { this.name = name; this.description = description; } public string Name { get { return name; } set { name = value; } } public string Description { get { return description; } set { description = value; } } private string name; private string description; } public class LYLDataObjCol : ObservableCollection<LYLDataObj> { public LYLDataObjCol() { this.Add(new LYLDataObj("Microsot", "Operating System")); this.Add(new LYLDataObj("Google", "Search")); } } }
绑定之后,只要我的LYLDataObjCol对象发送了变化,ListBox、ComboBox的数据也会有对应的变化。<ListBox ItemsSource="{StaticResource dataObj}" .../>
到现在,我们已经知道在绑定的时候有两种指定数据源的方式:1、DataContext,关于它我们在这个Post有简单介绍。2、直接用Binding类的Source属性。那么,我们在使用的时候如何区别呢?首先,Source的优先级比DataContext高,只有Source不存在,或者在当前Source到不到需要的属性时才会查找DataContext。除此之外,这两者没有真正的区别,只是建议使用Source,它能有助于我们调试应用程序。因为通过它可以明确的得到Source的信息。而DataContext支持一种继承。可以在父Element指定Source源。这同时也成为了DataContext的一个优点:如果多个Element需要绑定同一个Source源,那么我们只需要在一个地方指定DataContext,就可以在其子Element使用。