深入浅出WPF之Binding的使用(一)
from: ??http://www.cnblogs.com/akwwl/p/3421005.html
在WPF中Binding可以比作數(shù)據(jù)的橋梁,橋梁的兩端分別是Binding的源(Source)和目標(biāo)(Target)。
一般情況下,Binding源是邏輯層對(duì)象,Binding目標(biāo)是UI層的控件對(duì)象;這樣,數(shù)據(jù)就會(huì)通過(guò)Binding送達(dá)UI層,被UI層展現(xiàn)。
? 首先我們創(chuàng)建一個(gè)名為Student的類(lèi),這個(gè)類(lèi)的實(shí)例作為數(shù)據(jù)源在UI上顯示:
public class Student{private string name;public string Name{set { name = value; }get { return name; }}}Binding是一種自動(dòng)機(jī)制,當(dāng)值變化后屬性要有能力通知Binding,讓Binding把變化傳遞給UI元素。
怎樣才能讓一個(gè)屬性具備這種通知Binding值已經(jīng)變化的能力呢?方法是在屬性的set語(yǔ)句中激發(fā)一個(gè)PropertyChanged事件。這個(gè)事件不需要我們自己聲明,我們要做的是讓作為數(shù)據(jù)源的類(lèi)實(shí)現(xiàn)System.ComponentModel名稱(chēng)空間中的INotifyPropertyChanged接口。當(dāng)為Binding設(shè)置了數(shù)據(jù)源后,Binding就會(huì)自動(dòng)偵聽(tīng)來(lái)自這個(gè)接口的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));}}}當(dāng)Name屬性的值發(fā)生變化時(shí)PropertyChanged事件就會(huì)被激發(fā),Binding接收到這個(gè)事件后發(fā)現(xiàn)事件的消息告訴它是名為Name的屬性發(fā)生了值得改變,于是就會(huì)通知Binding目標(biāo)端的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類(lèi)型變量并創(chuàng)建實(shí)例,
然后使用binding.Source=student為Binding實(shí)例指定數(shù)據(jù)源,
最后使用binding.Path = new PropertyPath("Name")為Binding指定訪(fǎng)問(wèn)路徑。
把數(shù)據(jù)源和目標(biāo)連接在一起的任務(wù)是使用BindingOperations.SetBinding(this.Box,TextBox.TextProperty,binding)方法完成的。
BindingOperations.SetBinding(this.Box, ? ?TextBox.TextProperty, ? ?binding)中的參數(shù)介紹:
第一個(gè)參數(shù)主要是指定Binding的目標(biāo)。
第二個(gè)參數(shù)是用于為Binding指明將數(shù)據(jù)綁定到目標(biāo)的那個(gè)屬性中去,一般都為目標(biāo)的依賴(lài)屬性。
第三個(gè)參數(shù)是指定那個(gè)Binding將數(shù)據(jù)源與目標(biāo)關(guān)聯(lián)起來(lái)。
上面的代碼還可以簡(jiǎn)化如下:
private void SetBinding(){student = new Student();this.Box.SetBinding(TextBox.TextProperty, new Binding("Name") { Source=student});}?
Binding模型如下:
總結(jié)
以上是生活随笔為你收集整理的深入浅出WPF之Binding的使用(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 解读沃指数APP排行榜的三大亮点:垂直领
- 下一篇: 览沃livox_大疆览沃浩界(Livox