WPF(Windows Presentation Fundation) databinding功能能很好的顯示listbox, listview中的內容.在其中有四個(gè)要素:1.綁定目標(binding target), 2. 目標屬性(target property), 3.綁定的源數據( binding source), 4. 綁定的屬性,通過(guò)關(guān)鍵字Path來(lái)指定( a path to the source to use)如下圖:
數據綁定幾個(gè)必要做的事:
1. 實(shí)現 INotifyPorpertyChanged接口,
2.有屬性改變時(shí)通過(guò)PropertyChangedEventHandler來(lái)捕捉
3.ObservableCollection是INotifyPropertyChanged內建的實(shí)現數據綁定.
4.XAML文件中必需添加xmlns:<YourSpecifiedName>="clr-namespace:YourNameSpace"
好,讓我們來(lái)看一個(gè)具體的例子.創(chuàng )建一個(gè)WPF應用程序,采用C#來(lái)做.
文件 Data.cs:
using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace Collections
{
public class Person : INotifyPropertyChanged
{
//the person‘s attribute sex
private string name;
private string sex;
public event PropertyChangedEventHandler PropertyChanged;
//person constructor
public Person()
{
}
public Person(string named, string sexy)
{
this.name = named;
this.sex = sexy;
}
//person name attribute
public string Name
{
get { return name; }
set
{
this.name = ;
OnPropertyChanged("Name");
}
}
//person sex attribute
public string Sex
{
get { return sex; }
set
{
this.sex = ;
OnPropertyChanged("Sex");
}
}
//override the ToString method for dispaly Person‘s name
// if not override it, it will be displayed as "Collections.Person" but not person‘s name
public override string ToString()
{
return name.ToString();
}
//cacth up the property changed event
protected void OnPropertyChanged(string inputstring)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this,new PropertyChangedEventArgs(inputstring));
}
}
}
public class People : ObservableCollection<Person>
{
public People():base()
{
Add(new Person("Ekin", "Male"));
Add(new Person("Jack", "Male"));
Add(new Person("Jane", "Female"));
}
}
}
Windows1.xaml文件,注意XAML文件必需保持父子層嚴格的縮進(jìn).
<Window x:Class="Collections.Window1"
xmlns="