1、自定義類做爲源綁定到TextBlock函數
1.新建一個Student類this
public class Student { public Student(string name) { this.Name = name; } public string Name { get; set; } }
2.將Student的Name屬性綁定到TextBlockspa
Student Stu = new Student("Pitter");
//在窗體的構造函數中綁定 public MainWindow() { InitializeComponent(); Binding bind = new Binding(); bind.Source = student; bind.Path = new PropertyPath("Name"); //指定Binding 目標和目標屬性 tbName.SetBinding(TextBlock.TextProperty, bind); }
運行效果以下:code
3.但此時的Name屬性不具有通知Binding的能力,即當數據源(Stu的Name屬性)發生變化時,Binding不能同時更新目標的中數據blog
添加一個Button按鈕驗證接口
Student Stu = new Student("Pitter"); //在窗體的構造函數中綁定 public MainWindow() { InitializeComponent(); Binding bind = new Binding(); bind.Source = Stu; bind.Path = new PropertyPath("Name"); //指定Binding 目標和目標屬性 tbName.SetBinding(TextBlock.TextProperty, bind); } private void btName_Click(object sender, RoutedEventArgs e) { Stu.Name = "Harry"; }
此時點擊Button按鈕時,TextBlock內容不會發生任何變化get
解決方法就是給Student類實現一個接口:INotifyPropertyChanged(位於命名空間:System.ComponentModel)string
public class Student: INotifyPropertyChanged { private string name; public Student(string name) { this.Name = name; } public string Name { get { return name; } set { name = value; if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Name")); } }
public event PropertyChangedEventHandler PropertyChanged; }
這時再點擊按鈕文本就會發生改變it