from: ??http://www.cnblogs.com/akwwl/p/3421005.html
在WPF中Binding可以比作數據的橋梁,橋梁的兩端分別是Binding的源(Source)和目標(Target)。
一般情況下,Binding源是邏輯層對象,Binding目標是UI層的控件對象;這樣,數據就會通過Binding送達UI層,被UI層展現。
? 首先我們創建一個名為Student的類,這個類的實例作為數據源在UI上顯示:
public class Student{private string name;public string Name{set { name = value; }get { return name; }}}
Binding是一種自動機制,當值變化后屬性要有能力通知Binding,讓Binding把變化傳遞給UI元素。
怎樣才能讓一個屬性具備這種通知Binding值已經變化的能力呢?方法是在屬性的set語句中激發一個PropertyChanged事件。這個事件不需要我們自己聲明,我們要做的是讓作為數據源的類實現System.ComponentModel名稱空間中的INotifyPropertyChanged接口。當為Binding設置了數據源后,Binding就會自動偵聽來自這個接口的PropertyChanged事件。
public class Student:INotifyPropertyChanged{private string name;public string Name{set { name = value;NotifyPropertyChanged("Name");}get { return name; }}public event PropertyChangedEventHandler PropertyChanged;private void NotifyPropertyChanged(string propertyName){if (PropertyChanged != null){PropertyChanged(this,new PropertyChangedEventArgs(propertyName));}}}
當Name屬性的值發生變化時PropertyChanged事件就會被激發,Binding接收到這個事件后發現事件的消息告訴它是名為Name的屬性發生了值得改變,于是就會通知Binding目標端的UI元素顯示新的值。
XAML代碼:
<Grid><TextBox x:Name="Box" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="100,50,0,0" Height="30" Width="200"/><Button Content="按鈕" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="120,150,0,0" Height="30" Width="160" Click="Button_Click"/></Grid>
C#代碼:
public partial class MainWindow : Window{private Student student;public MainWindow(){InitializeComponent();student = new Student();Binding binding = new Binding();binding.Source = student;binding.Path = new PropertyPath("Name");BindingOperations.SetBinding(this.Box,TextBox.TextProperty,binding);}private void Button_Click(object sender, RoutedEventArgs e){student.Name = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");}}
其中:Binding binding=new Binding()聲明Binding類型變量并創建實例,
然后使用binding.Source=student為Binding實例指定數據源,
最后使用binding.Path = new PropertyPath("Name")為Binding指定訪問路徑。
把數據源和目標連接在一起的任務是使用BindingOperations.SetBinding(this.Box,TextBox.TextProperty,binding)方法完成的。
BindingOperations.SetBinding(this.Box, ? ?TextBox.TextProperty, ? ?binding)中的參數介紹:
第一個參數主要是指定Binding的目標。
第二個參數是用于為Binding指明將數據綁定到目標的那個屬性中去,一般都為目標的依賴屬性。
第三個參數是指定那個Binding將數據源與目標關聯起來。
上面的代碼還可以簡化如下:
private void SetBinding(){student = new Student();this.Box.SetBinding(TextBox.TextProperty, new Binding("Name") { Source=student});}
?
Binding模型如下: