WPF提供了一個(gè)ObservableCollection類(lèi),它實(shí)現了一個(gè)暴露了INotifyPropertyChanged的數據集合。也就是說(shuō)我們不需要自己對每個(gè)單獨的數據實(shí)現INotifyPropertyChanged結構。我們先看看如何實(shí)現一個(gè)簡(jiǎn)單的綁定數據集合。
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"));
}
}
}
代碼很簡(jiǎn)單,基本上就是這樣的一個(gè)模板。然后,我們就可以把LYLDataObjCol綁定到一個(gè)需要多項數據的Element之上,比如ListBox、ComboBox等等。
<ListBox ItemsSource="{StaticResource dataObj}" .../>
綁定之后,只要我的LYLDataObjCol對象發(fā)送了變化,ListBox、ComboBox的數據也會(huì )有對應的變化。
到現在,我們已經(jīng)知道在綁定的時(shí)候有兩種指定數據源的方式:1、DataContext,關(guān)于它我們在這個(gè)Post有簡(jiǎn)單介紹。2、直接用Binding類(lèi)的Source屬性。那么,我們在使用的時(shí)候如何區別呢?首先,Source的優(yōu)先級比DataContext高,只有Source不存在,或者在當前Source到不到需要的屬性時(shí)才會(huì )查找DataContext。除此之外,這兩者沒(méi)有真正的區別,只是建議使用Source,它能有助于我們調試應用程序。因為通過(guò)它可以明確的得到Source的信息。而DataContext支持一種繼承??梢栽诟窫lement指定Source源。這同時(shí)也成為了DataContext的一個(gè)優(yōu)點(diǎn):如果多個(gè)Element需要綁定同一個(gè)Source源,那么我們只需要在一個(gè)地方指定DataContext,就可以在其子Element使用。
聯(lián)系客服