运行结果和解决方案管理截图如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace 完全数据绑定 { class Person : INotifyPropertyChanged//INotifyPropertyChanged是.net内置的接口,数据绑定会检测DataContext是否实现了INotifyPropertyChanged,如果实现了就会监听PropertyChanged这个属性改变的事件 { private string name;//定义名字 private int age;//定义年龄 public string Name { get; set; } public int Age//定义年龄属性 { get { return age;} set { this.age = value; if (PropertyChanged != null) { PropertyChanged(this,new PropertyChangedEventArgs("Age")); } } } public event PropertyChangedEventHandler PropertyChanged;//定义一个属性改变事件 } }
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 完全数据绑定 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private Person p1 = new Person();//定义一个字段并初始化 public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { p1.Name = "红马車"; p1.Age = 24; txtName.DataContext = p1; txtAge.DataContext = p1; } //增加年龄 private void btnAdd_Click(object sender, RoutedEventArgs e) { p1.Age++; } //显示年龄 private void btnShow_Click(object sender, RoutedEventArgs e) { MessageBox.Show(p1.Age.ToString()); } } }
可以说MVVM是专为WPF打造的模式, 也可以说MVVM仅仅是MVC的一个变种, 但无论如何, 就实践而言, 如果你或你的团队没有使用"Binding"的习惯, 那么研究MVVM就没有多大意义.