引用地址:http://blog.csdn.net/yl2isoft/article/details/20838149

1 新建WPF 应用程序WPFMVVMExample

程序结构如下图所示。

2 Model实现

在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细代码如下所示。

  1. using System.ComponentModel;
  2. namespace WPFMVVMExample.Model
  3. {
  4. public class StudentModel : INotifyPropertyChanged
  5. {
  6. /// <summary>
  7. /// 学号
  8. /// </summary>
  9. private int studentId;
  10. public int StudentId
  11. {
  12. get
  13. {
  14. return studentId;
  15. }
  16. set
  17. {
  18. studentId = value;
  19. NotifyPropertyChanged("StudentId");
  20. }
  21. }
  22. /// <summary>
  23. /// 姓名
  24. /// </summary>
  25. private string studentName;
  26. public string StudentName
  27. {
  28. get
  29. {
  30. return studentName;
  31. }
  32. set
  33. {
  34. studentName = value;
  35. NotifyPropertyChanged("StudentName");
  36. }
  37. }
  38. /// <summary>
  39. /// 年龄
  40. /// </summary>
  41. private int studentAge;
  42. public int StudentAge
  43. {
  44. get
  45. {
  46. return studentAge;
  47. }
  48. set
  49. {
  50. studentAge = value;
  51. NotifyPropertyChanged("StudentAge");
  52. }
  53. }
  54. /// <summary>
  55. /// Email
  56. /// </summary>
  57. private string studentEmail;
  58. public string StudentEmail
  59. {
  60. get
  61. {
  62. return studentEmail;
  63. }
  64. set
  65. {
  66. studentEmail = value;
  67. NotifyPropertyChanged("StudentEmail");
  68. }
  69. }
  70. /// <summary>
  71. /// 性别
  72. /// </summary>
  73. private string studentSex;
  74. public string StudentSex
  75. {
  76. get
  77. {
  78. return studentSex;
  79. }
  80. set
  81. {
  82. studentSex = value;
  83. NotifyPropertyChanged("StudentSex");
  84. }
  85. }
  86. public event PropertyChangedEventHandler PropertyChanged;
  87. public void NotifyPropertyChanged(string propertyName)
  88. {
  89. if (PropertyChanged != null)
  90. {
  91. PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  92. }
  93. }
  94. }
  95. }

StudentModel类实现了接口INotifyPropertyChanged。当类实现该接口后,便可以向执行绑定的客户端发出某一属性值已更改的通知。

3 ViewModel实现

在ViewModel文件夹下新建类文件StudentViewModel.cs,类文件的详细代码如下所示。

  1. using System;
  2. using System.Windows.Input;
  3. using WPFMVVMExample.Model;
  4. namespace WPFMVVMExample.ViewModel
  5. {
  6. public class StudentViewModel
  7. {
  8. public DelegateCommand ShowCommand { get; set; }
  9. public StudentModel Student { get; set; }
  10. public StudentViewModel()
  11. {
  12. Student = new StudentModel();
  13. ShowCommand=new DelegateCommand();
  14. ShowCommand.ExecuteCommand = new Action<object>(ShowStudentData);
  15. }
  16. private void ShowStudentData(object obj)
  17. {
  18. Student.StudentId = 1;
  19. Student.StudentName = "tiana";
  20. Student.StudentAge = 20;
  21. Student.StudentEmail = "8644003248@qq.com";
  22. Student.StudentSex = "大帅哥";
  23. }
  24. }
  25. public class DelegateCommand : ICommand
  26. {
  27. public Action<object> ExecuteCommand = null;
  28. public Func<object, bool> CanExecuteCommand = null;
  29. public event EventHandler CanExecuteChanged;
  30. public bool CanExecute(object parameter)
  31. {
  32. if (CanExecuteCommand != null)
  33. {
  34. return this.CanExecuteCommand(parameter);
  35. }
  36. else
  37. {
  38. return true;
  39. }
  40. }
  41. public void Execute(object parameter)
  42. {
  43. if (this.ExecuteCommand != null)
  44. {
  45. this.ExecuteCommand(parameter);
  46. }
  47. }
  48. public void RaiseCanExecuteChanged()
  49. {
  50. if (CanExecuteChanged != null)
  51. {
  52. CanExecuteChanged(this, EventArgs.Empty);
  53. }
  54. }
  55. }
  56. }

代码中,除了定义StudentViewModel类外,还定义了DelegateCommand类,该类实现了ICommand接口。

ICommand接口中的Execute()方法用于命令的执行,CanExecute()方法用于指示当前命令在目标元素上是否可用,当这种可用性发生改变时便会触发接口中的CanExecuteChanged事件。

我们可以将实现了ICommand接口的命令DelegateCommand赋值给Button(命令源)的Command属性(只有实现了ICommandSource接口的元素才拥有该属性),这样Button便与命令进行了绑定。

4 MainWindow.xaml实现

MainWindow.xaml的界面如下图所示。

MainWindow.xaml界面的xaml代码如下所示。

  1. <Window x:Class="WPFMVVMExample.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="MainWindow" Height="350" Width="525">
  5. <Grid>
  6. <Label Content="学号" Height="28" HorizontalAlignment="Left" Margin="54,23,0,0" Name="labelStudentId" VerticalAlignment="Top" />
  7. <TextBox Text="{Binding Student.StudentId}" IsReadOnly="True" Height="23" HorizontalAlignment="Right" Margin="0,27,289,0" Name="textBoxStudentId" VerticalAlignment="Top" Width="120" />
  8. <Label Content="姓名" Height="28" HorizontalAlignment="Left" Margin="54,61,0,0" Name="labelStudentName" VerticalAlignment="Top" />
  9. <TextBox Text="{Binding Student.StudentName}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,65,0,0" Name="textBoxStudentName" VerticalAlignment="Top" Width="120" />
  10. <Label Content="年龄" Height="28" HorizontalAlignment="Left" Margin="54,94,0,0" Name="labelStudentAge" VerticalAlignment="Top" />
  11. <TextBox Text="{Binding Student.StudentAge}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,99,0,0" Name="textBoxStudentAge" VerticalAlignment="Top" Width="120" />
  12. <Label Content="Email" Height="28" HorizontalAlignment="Left" Margin="50,138,0,0" Name="labelStudentEmail" VerticalAlignment="Top" />
  13. <TextBox Text="{Binding Student.StudentEmail}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,141,0,0" Name="textBoxStudentEmail" VerticalAlignment="Top" Width="120" />
  14. <Label Content="性别" Height="28" HorizontalAlignment="Left" Margin="57,176,0,0" Name="labelStudentSex" VerticalAlignment="Top" />
  15. <TextBox Text="{Binding Student.StudentSex}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,180,0,0" Name="textBoxStudentSex" VerticalAlignment="Top" Width="120" />
  16. <Button Command="{Binding ShowCommand}" Content="显示" Height="23" HorizontalAlignment="Left" Margin="345,27,0,0" Name="buttonShow" VerticalAlignment="Top" Width="75" />
  17. </Grid>
  18. </Window>

MainWindow.xaml的后端代码如下所示。

  1. using System.Windows;
  2. using WPFMVVMExample.ViewModel;
  3. namespace WPFMVVMExample
  4. {
  5. /// <summary>
  6. /// MainWindow.xaml 的交互逻辑
  7. /// </summary>
  8. public partial class MainWindow : Window
  9. {
  10. public MainWindow()
  11. {
  12. InitializeComponent();
  13. this.DataContext = new StudentViewModel();
  14. }
  15. }
  16. }

5 运行程序

运行程序,点击“显示”按钮,即将数据绑定至界面显示。

6 说明

WPF中使用MVVM可以降低UI显示与后端逻辑代码的耦合度,即更换界面时,只需要修改很少的逻辑代码就可以实现,甚至不用修改。

在WinForm开发中,我们一般会直接操作界面的元素(如:TextBox1.Text=“aaa”),这样一来,界面变化后,后端逻辑代码也需要做相应的变更。

在WPF中使用数据绑定机制,当数据变化后,数据会通知界面变更的发生,而不需要通过访问界面元素来修改值,这样在后端逻辑代码中也就不必操作或者很少操作界面的元素了。

使用MVVM,可以很好的配合WPF的数据绑定机制来实现UI与逻辑代码的分离,MVVM中的View表示界面,负责页面显示,ViewModel负责逻辑处理,包括准备绑定的数据和命令,ViewModel通过View的DataContext属性绑定至View,Model为业务模型,供ViewModel使用。

一个简单的WPF MVVM实例【转载】的更多相关文章

  1. WInform 创建一个简单的WPF应用

    (一)创建一个简单的WPF应用 首先,在这里我要说明的是:这里的例子,都是通过控制台程序来创建WPF应用,而非使用现成的WPF模版.因为WPF模版封装了创建WPF应用所需要的各种基本元素,并不利于我们 ...

  2. 一个简单的Android小实例

    原文:一个简单的Android小实例 一.配置环境 1.下载intellij idea15 2.安装Android SDK,通过Android SDK管理器安装或卸载Android平台   3.安装J ...

  3. 一个简单的jQuery插件开发实例

    两年前写的一个简单的jQuery插件开发实例,还是可以看看的: <script type="text/javascript" src="jquery-1.7.2.m ...

  4. [WCF REST] 一个简单的REST服务实例

    Get:http://www.cnblogs.com/artech/archive/2012/02/04/wcf-rest-sample.html [01] 一个简单的REST服务实例 [02] We ...

  5. PureMVC和Unity3D的UGUI制作一个简单的员工管理系统实例

    前言: 1.关于PureMVC: MVC框架在很多项目当中拥有广泛的应用,很多时候做项目前人开坑开了一半就消失了,后人为了填补各种的坑就遭殃的不得了.嘛,程序猿大家都不喜欢像文案策划一样组织文字写东西 ...

  6. 制作一个简单的WPF图片浏览器

    原文:制作一个简单的WPF图片浏览器 注:本例选自MSDN样例,并略有改动.先看效果: 这里实现了以下几个功能:1.  对指定文件夹下所有JPG文件进行预览2.  对选定图片进行旋转3.  对选定图片 ...

  7. 一个简单的window.onscroll实例

    鉴于better-scroll实现这个效果很复杂,想用最原生的效果来实现吸顶效果 一个简单的window.onscroll实例,可以应用于移动端 demo 一个简单的window.onscroll实例 ...

  8. WPF MVVM实例三

    在没给大家讲解wpf mwm示例之前先给大家简单说下MVVM理论知识: WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时 ...

  9. Web开发之tomcat配置及使用(环境变量设置及测试,一个简单的web应用实例)

    Tomcat的配置及测试: 第一步:下载tomcat,然后解压到任意盘符 第二步:配置系统环境变量 tomcat解压到的D盘 (路径为: D:\tomcat), 配置环境变量: 启动tomcat需要两 ...

随机推荐

  1. 调用webservice

    WebClient web = new WebClient(); Stream stream = web.OpenRead(this._wsdlUrl); //Stream streamInfo = ...

  2. LayUI&前端问题汇总

    1.用JS获取地址栏参数的方法 采用正则表达式获取地址栏参数:( 强烈推荐,既实用又方便!) //通过data给form赋值,根据name赋给value $.fn.setForm = function ...

  3. 零度4W1H提问规则

    WHAT:您现在的需求和目的是什么,请按条理描述清楚. WHERE:在什么平台.环境和工具下发生此问题. WHEN:何时发生的该问题,该问题是否能够重现. WHY:为什么不能通过搜索引擎来解决您的问题 ...

  4. 修复kindEditor点击加粗, 内容焦点跳动的问题

    大概1560~1569行 pos : function() { var self = this, node = self[0], x = 0, y = 0; if (node) { if (node. ...

  5. springboot Aop配置,并使用自定义注解annotation,并且拦截service层

    前言 用Spring Boot的AOP来简化处理自定义注解,并将通过实现一个简单的方法执行判断节点是否开始的状态示列源码. AOP概念 面向侧面的程序设计(aspect-oriented progra ...

  6. IDEA检出SVN项目

    https://blog.csdn.net/qq_27093465/article/details/74898489 https://jingyan.baidu.com/article/47a29f2 ...

  7. spring-cloud构架微服务(1)-全局配置

    使用spring-cloud是基于熟悉springboot基础上进行的.本篇介绍全局配置,spring-boot版本就以1.4.0来做吧.项目地址: https://git.oschina.net/b ...

  8. Unity利用AnimationCurve做物体的各种运动

    ​之前一直都是自己学习Unity各种做Demo,最近开始正式使用Unity来做一个款2d的游戏. 其中在做一个类似小球弹跳运动的时候遇到了点问题,查找了很多资料,无意间发现AnimationCurve ...

  9. Node.js-ReferenceError: _filename is not defined

    简直不要被坑得太惨!!!你能?看出来这前面是两根下划线!两根下划线!两根下划线!太尴尬了~找了半天原因居然是这个!

  10. 使用ABAP代码创建S/4HANA里的Sales Order

    下图是使用ABAP代码创建的S/4HANA的Sales Order的截图: 其中红色区域的值是我代码里硬编码的,而蓝色是函数SD_SALESDOCUMENT_CREATE自己创建的. 来看下代码: D ...