SilverLight學習筆記之三資料繫結方式(上)

來源:互聯網
上載者:User

 在 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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.