MVVM模式中WPF数据的完全绑定
2014-08-21 11:31
351 查看
一:截图,描述:将后台代码的姓名、年龄绑定到文本框,单击”增加年龄“--年龄自+1,单击”显示年龄“--弹出年龄的显示对话框,实现了从文本框修改年龄和后台更改年龄并显示到文本框
运行结果和解决方案管理截图如下:
二:person类
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?
可以说MVVM是专为WPF打造的模式, 也可以说MVVM仅仅是MVC的一个变种, 但无论如何, 就实践而言, 如果你或你的团队没有使用"Binding"的习惯, 那么研究MVVM就没有多大意义.相关文章推荐
- MVVM模式和在WPF中的实现(二)数据绑定
- MVVM模式WPF的ComboBox数据绑定,使用Dictionary作为数据源
- WPF中使用MVVM模式进行简单的数据绑定
- Mvvm Light Toolkit for wpf/silverlight系列之数据绑定
- Windows Phone 7中对于 MVVM模式的数据绑定和参数传递(转)
- MVVM设计模式和WPF中的实现(四)事件绑定
- MVVM设计模式和WPF中的实现 (事件绑定)
- uwp开发:MVVM模式和数据绑定结合使用实战示例
- Windows Phone 7 MVVM模式数据绑定和传递参数
- 第5篇 WPF C# 数据绑定Model-View-ViewModel模式
- WPF Prism框架下基于MVVM模式的命令、绑定、事件
- 们只是「电脑玩物」 首页 实用技巧 免费资源 超好玩的游戏 软件推荐 IT技术 资讯 编程 其它 MVVM设计模式和WPF中的实现(四) 事件绑定 07net01.com 发布于 2015-10-08
- wpf数据绑定的三种模式:oneTime、OneWay、.TwoWay
- WPF数据绑定之4种绑定模式
- wpf 在MVVM模式下开发时,怎样让一个属性绑定到多个RadioButton上
- Windows Phone 7 MVVM模式数据绑定和传递参数
- Silverlight之MVVM模式简单介绍项目(数据绑定)
- Windows Phone 7 MVVM模式数据绑定和传递参数
- 【转】Mvvm Light Toolkit for wpf/silverlight系列之数据绑定
- WPF学习笔记:(二)数据绑定模式与INotifyPropertyChanged接口