1)数据源
添加一个Student类:
(Binding是一种自动机制,当值变化后属性要有能力通知Binding,让Binding把变化传递给UI元素。方法是在属性set语句中激发一个PropertyChanged事件。这个事件不用我们声明,我们要做到的是让作为数据源的类实现System.ComponentModel名称空间中的INotifyPropertyChanged接口。当为Binding设置了数据源后,Binding就会自动监听来自这个接口的PropertyChanged事件。)
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;namespace TestBinding{ class Student:INotifyPropertyChanged//实现这个接口,让Binding自动监听 { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激发事件 if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } }}
或者:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;namespace TestBinding{ class Student:INotifyPropertyChanged//实现这个接口,让Binding自动监听 { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激发事件 PropertyChangedEventHandler handler = PropertyChanged; if (this.PropertyChanged != null) { //this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); handler(this, new PropertyChangedEventArgs("Name")); } } } }}
2)编写前台代码:
XAML:
3)使用Binding把数据源和UI元素连接起来
C#:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace TestBinding{ ////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { Student stu; public MainWindow() { InitializeComponent(); /* //准备数据源 stu = new Student(); //准备Binding Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name");//为Binding指定访问路径 //使用Binding连接数据源与Binding目标 BindingOperations.SetBinding(textBoxName, TextBox.TextProperty, binding); */ //以上三合一的做法: this.textBoxName.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu = new Student() }); //this.textBoxName.SetBinding(TextBox.TextProperty, new Binding() { Source = stu = new Student(),Path=new PropertyPath("Name") }); } private void Button_Click(object sender, RoutedEventArgs e) { stu.Name += "Name"; } }}
截图: