WPF 数据绑定(Binding)(一)-自定义类做为源(Source)

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

相关文章
相关标签/搜索