一、自定义类作为源绑定到TextBlock
1.新建一个Student类
public class Student { public Student(string name) { this.Name = name; } public string Name { get; set; } }
2.将Student的Name属性绑定到TextBlock
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); }
运行效果如下:
3.但此时的Name属性不具备通知Binding的能力,即当数据源(Stu的Name属性)发生变化时,Binding不能同时更新目标的中数据
添加一个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内容不会发生任何变化
解决方法就是给Student类实现一个接口:INotifyPropertyChanged(位于命名空间:System.ComponentModel)
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; }
这时再点击按钮文本就会发生改变