在 Silverlight 中支援3種綁定:OneWay, TwoWay, OneTime. 預設是 OneWay.
其中 OneWay 表示僅僅從資料來源綁定到目標(通常是 UI 對象),單向的;
TwoWay 表示既可以從資料來源綁定到目標,目標的更改也可以反饋給資料來源,使其發生更新。
而 OneTime 是 OneWay 的一種特例,僅載入一次資料。隨後資料的變更不會通知繫結目標對象。這樣,可以帶來更好的效能。
綁定的文法可以用大括弧表示,下面是幾個例子:
<TextBlockText="{Binding Age}"/>
等同於:
<TextBlock Text="{Binding Path=Age}" />
或者顯式寫出綁定方向:
<TextBlock Text="{Binding Path=Age, Mode=OneWay}" />
按照資料繫結的語義,預設是 OneWay 的,也就是說如果背景資料發生變化,前台建立了綁定關係的相關控制項也應該發生更新。
比如我們可以將文章 (1) 中提到的資料來源改為當前頁面的一個私人成員,然後在某個 Button 點擊事件中更改其中的值。代碼如下:
public partial class Page : UserControl{private List<Person> persons;public Page(){InitializeComponent();persons = new List<Person>();for(var i=0; i< 5; i++){persons.Add(new Person {Name = "Person " + i.ToString(), Age = 20 + i});}list1.DataContext = persons;}private void Button_Click(object sender, RoutedEventArgs e){persons[0].Name = "Tom";}}
<ListBox x:Name="list1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Age}" Margin="20,0" /> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
但是我們點擊 Button 發現 ListBox 裡的資料並沒有發生變化。這是因為在資料來源更新時,並沒有發出任何通知。
我們可以讓資料來源中的對象實現 INotifyPropertyChanged 介面,在綁定的源屬性值發生變化時,發出相關的通知資訊。
代碼如下:
public class Person: INotifyPropertyChanged{private int age;public int Age{get{return age;}set{age = value;NotifyPropertyChange("Age");}}private string name;public string Name {get{return name;}set{name = value;NotifyPropertyChange("Name");}}public event PropertyChangedEventHandler PropertyChanged;private void NotifyPropertyChange(string propertyName){if(PropertyChanged != null){PropertyChanged(this, new PropertyChangedEventArgs(propertyName));}}}
這個代碼的原理很簡單,這裡就不解釋了。這樣以後,點擊按鈕,前台的 ListBox 中第一條資料的人名就變成了 Tom:
http://www.cnblogs.com/RChen/archive/2008/07/03/1235039.html